home *** CD-ROM | disk | FTP | other *** search
/ Meeting Pearls 1 / Meeting Pearls Vol 1 (1994).iso / installed_progs / text / faqs / c-faq.faq < prev    next >
Encoding:
Internet Message Format  |  1994-05-02  |  143.1 KB

  1. Subject: comp.lang.c Answers to Frequently Asked Questions (FAQ List)
  2. Newsgroups: comp.lang.c,comp.answers,news.answers
  3. From: scs@eskimo.com (Steve Summit)
  4. Date: 1 May 94 10:02:39 GMT
  5.  
  6. Archive-name: C-faq/faq
  7. Comp-lang-c-archive-name: C-FAQ-list
  8.  
  9. [Last modified April 16, 1994 by scs.]
  10.  
  11. Certain topics come up again and again on this newsgroup.  They are good
  12. questions, and the answers may not be immediately obvious, but each time
  13. they recur, much net bandwidth and reader time is wasted on repetitive
  14. responses, and on tedious corrections to the incorrect answers which are
  15. inevitably posted.
  16.  
  17. This article, which is posted monthly, attempts to answer these common
  18. questions definitively and succinctly, so that net discussion can move
  19. on to more constructive topics without continual regression to first
  20. principles.
  21.  
  22. No mere newsgroup article can substitute for thoughtful perusal of a
  23. full-length tutorial or language reference manual.  Anyone interested
  24. enough in C to be following this newsgroup should also be interested
  25. enough to read and study one or more such manuals, preferably several
  26. times.  Some C books and compiler manuals are unfortunately inadequate;
  27. a few even perpetuate some of the myths which this article attempts to
  28. refute.  Several noteworthy books on C are listed in this article's
  29. bibliography.  Many of the questions and answers are cross-referenced to
  30. these books, for further study by the interested and dedicated reader
  31. (but beware of ANSI vs. ISO C Standard section numbers; see question
  32. 5.1).
  33.  
  34. If you have a question about C which is not answered in this article,
  35. first try to answer it by checking a few of the referenced books, or by
  36. asking knowledgeable colleagues, before posing your question to the net
  37. at large.  There are many people on the net who are happy to answer
  38. questions, but the volume of repetitive answers posted to one question,
  39. as well as the growing number of questions as the net attracts more
  40. readers, can become oppressive.  If you have questions or comments
  41. prompted by this article, please reply by mail rather than following up
  42. -- this article is meant to decrease net traffic, not increase it.
  43.  
  44. Besides listing frequently-asked questions, this article also summarizes
  45. frequently-posted answers.  Even if you know all the answers, it's worth
  46. skimming through this list once in a while, so that when you see one of
  47. its questions unwittingly posted, you won't have to waste time
  48. answering.
  49.  
  50. This article is always being improved.  Your input is welcomed.  Send
  51. your comments to scs@eskimo.com .
  52.  
  53. The questions answered here are divided into several categories:
  54.  
  55.      1. Null Pointers
  56.      2. Arrays and Pointers
  57.      3. Memory Allocation
  58.      4. Expressions
  59.      5. ANSI C
  60.      6. C Preprocessor
  61.      7. Variable-Length Argument Lists
  62.      8. Boolean Expressions and Variables
  63.      9. Structs, Enums, and Unions
  64.     10. Declarations
  65.     11. Stdio
  66.     12. Library Subroutines
  67.     13. Lint
  68.     14. Style
  69.     15. Floating Point
  70.     16. System Dependencies
  71.     17. Miscellaneous (Fortran to C converters, YACC grammars, etc.)
  72.  
  73. Herewith, some frequently-asked questions and their answers:
  74.  
  75.  
  76. Section 1. Null Pointers
  77.  
  78. 1.1:    What is this infamous null pointer, anyway?
  79.  
  80. A:    The language definition states that for each pointer type, there
  81.     is a special value -- the "null pointer" -- which is
  82.     distinguishable from all other pointer values and which is not
  83.     the address of any object or function.  That is, the address-of
  84.     operator & will never yield a null pointer, nor will a
  85.     successful call to malloc.  (malloc returns a null pointer when
  86.     it fails, and this is a typical use of null pointers: as a
  87.     "special" pointer value with some other meaning, usually "not
  88.     allocated" or "not pointing anywhere yet.")
  89.  
  90.     A null pointer is conceptually different from an uninitialized
  91.     pointer.  A null pointer is known not to point to any object; an
  92.     uninitialized pointer might point anywhere.  See also questions
  93.     3.1, 3.13, and 17.1.
  94.  
  95.     As mentioned in the definition above, there is a null pointer
  96.     for each pointer type, and the internal values of null pointers
  97.     for different types may be different.  Although programmers need
  98.     not know the internal values, the compiler must always be
  99.     informed which type of null pointer is required, so it can make
  100.     the distinction if necessary (see below).
  101.  
  102.     References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S
  103.     Sec. 5.3 p. 91; ANSI Sec. 3.2.2.3 p. 38.
  104.  
  105. 1.2:    How do I "get" a null pointer in my programs?
  106.  
  107. A:    According to the language definition, a constant 0 in a pointer
  108.     context is converted into a null pointer at compile time.  That
  109.     is, in an initialization, assignment, or comparison when one
  110.     side is a variable or expression of pointer type, the compiler
  111.     can tell that a constant 0 on the other side requests a null
  112.     pointer, and generate the correctly-typed null pointer value.
  113.     Therefore, the following fragments are perfectly legal:
  114.  
  115.         char *p = 0;
  116.         if(p != 0)
  117.  
  118.     However, an argument being passed to a function is not
  119.     necessarily recognizable as a pointer context, and the compiler
  120.     may not be able to tell that an unadorned 0 "means" a null
  121.     pointer.  For instance, the Unix system call "execl" takes a
  122.     variable-length, null-pointer-terminated list of character
  123.     pointer arguments.  To generate a null pointer in a function
  124.     call context, an explicit cast is typically required, to force
  125.     the 0 to be in a pointer context:
  126.  
  127.         execl("/bin/sh", "sh", "-c", "ls", (char *)0);
  128.  
  129.     If the (char *) cast were omitted, the compiler would not know
  130.     to pass a null pointer, and would pass an integer 0 instead.
  131.     (Note that many Unix manuals get this example wrong.)
  132.  
  133.     When function prototypes are in scope, argument passing becomes
  134.     an "assignment context," and most casts may safely be omitted,
  135.     since the prototype tells the compiler that a pointer is
  136.     required, and of which type, enabling it to correctly convert
  137.     unadorned 0's.  Function prototypes cannot provide the types for
  138.     variable arguments in variable-length argument lists, however,
  139.     so explicit casts are still required for those arguments.  It is
  140.     safest always to cast null pointer function arguments, to guard
  141.     against varargs functions or those without prototypes, to allow
  142.     interim use of non-ANSI compilers, and to demonstrate that you
  143.     know what you are doing.  (Incidentally, it's also a simpler
  144.     rule to remember.)
  145.  
  146.     Summary:
  147.  
  148.         Unadorned 0 okay:    Explicit cast required:
  149.  
  150.         initialization        function call,
  151.                     no prototype in scope
  152.         assignment
  153.                     variable argument in
  154.         comparison        varargs function call
  155.  
  156.         function call,
  157.         prototype in scope,
  158.         fixed argument
  159.  
  160.     References: K&R I Sec. A7.7 p. 190, Sec. A7.14 p. 192; K&R II
  161.     Sec. A7.10 p. 207, Sec. A7.17 p. 209; H&S Sec. 4.6.3 p. 72; ANSI
  162.     Sec. 3.2.2.3 .
  163.  
  164. 1.3:    What is NULL and how is it #defined?
  165.  
  166. A:    As a matter of style, many people prefer not to have unadorned
  167.     0's scattered throughout their programs.  For this reason, the
  168.     preprocessor macro NULL is #defined (by <stdio.h> or
  169.     <stddef.h>), with value 0 (or (void *)0, about which more
  170.     later).  A programmer who wishes to make explicit the
  171.     distinction between 0 the integer and 0 the null pointer can
  172.     then use NULL whenever a null pointer is required.  This is a
  173.     stylistic convention only; the preprocessor turns NULL back to 0
  174.     which is then recognized by the compiler (in pointer contexts)
  175.     as before.  In particular, a cast may still be necessary before
  176.     NULL (as before 0) in a function call argument.  (The table
  177.     under question 1.2 above applies for NULL as well as 0.)
  178.  
  179.     NULL should _only_ be used for pointers; see question 1.8.
  180.  
  181.     References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S
  182.     Sec. 13.1 p. 283; ANSI Sec. 4.1.5 p. 99, Sec. 3.2.2.3 p. 38,
  183.     Rationale Sec. 4.1.5 p. 74.
  184.  
  185. 1.4:    How should NULL be #defined on a machine which uses a nonzero
  186.     bit pattern as the internal representation of a null pointer?
  187.  
  188. A:    Programmers should never need to know the internal
  189.     representation(s) of null pointers, because they are normally
  190.     taken care of by the compiler.  If a machine uses a nonzero bit
  191.     pattern for null pointers, it is the compiler's responsibility
  192.     to generate it when the programmer requests, by writing "0" or
  193.     "NULL," a null pointer.  Therefore, #defining NULL as 0 on a
  194.     machine for which internal null pointers are nonzero is as valid
  195.     as on any other, because the compiler must (and can) still
  196.     generate the machine's correct null pointers in response to
  197.     unadorned 0's seen in pointer contexts.
  198.  
  199. 1.5:    If NULL were defined as follows:
  200.  
  201.         #define NULL ((char *)0)
  202.  
  203.     wouldn't that make function calls which pass an uncast NULL
  204.     work?
  205.  
  206. A:    Not in general.  The problem is that there are machines which
  207.     use different internal representations for pointers to different
  208.     types of data.  The suggested #definition would make uncast NULL
  209.     arguments to functions expecting pointers to characters to work
  210.     correctly, but pointer arguments to other types would still be
  211.     problematical, and legal constructions such as
  212.  
  213.         FILE *fp = NULL;
  214.  
  215.     could fail.
  216.  
  217.     Nevertheless, ANSI C allows the alternate
  218.  
  219.         #define NULL ((void *)0)
  220.  
  221.     definition for NULL.  Besides helping incorrect programs to work
  222.     (but only on machines with homogeneous pointers, thus
  223.     questionably valid assistance) this definition may catch
  224.     programs which use NULL incorrectly (e.g. when the ASCII  NUL
  225.     character was really intended; see question 1.8).
  226.  
  227.     References: ANSI Rationale Sec. 4.1.5 p. 74.
  228.  
  229. 1.6:    I use the preprocessor macro
  230.  
  231.         #define Nullptr(type) (type *)0
  232.  
  233.     to help me build null pointers of the correct type.
  234.  
  235. A:    This trick, though popular in some circles, does not buy much.
  236.     It is not needed in assignments and comparisons; see question
  237.     1.2.  It does not even save keystrokes.  Its use suggests to the
  238.     reader that the author is shaky on the subject of null pointers,
  239.     and requires the reader to check the #definition of the macro,
  240.     its invocations, and _all_ other pointer usages much more
  241.     carefully.  See also question 8.1.
  242.  
  243. 1.7:    Is the abbreviated pointer comparison "if(p)" to test for non-
  244.     null pointers valid?  What if the internal representation for
  245.     null pointers is nonzero?
  246.  
  247. A:    When C requires the boolean value of an expression (in the if,
  248.     while, for, and do statements, and with the &&, ||, !, and ?:
  249.     operators), a false value is produced when the expression
  250.     compares equal to zero, and a true value otherwise.  That is,
  251.     whenever one writes
  252.  
  253.         if(expr)
  254.  
  255.     where "expr" is any expression at all, the compiler essentially
  256.     acts as if it had been written as
  257.  
  258.         if(expr != 0)
  259.  
  260.     Substituting the trivial pointer expression "p" for "expr," we
  261.     have
  262.  
  263.         if(p)    is equivalent to        if(p != 0)
  264.  
  265.     and this is a comparison context, so the compiler can tell that
  266.     the (implicit) 0 is a null pointer, and use the correct value.
  267.     There is no trickery involved here; compilers do work this way,
  268.     and generate identical code for both statements.  The internal
  269.     representation of a pointer does _not_ matter.
  270.  
  271.     The boolean negation operator, !, can be described as follows:
  272.  
  273.         !expr    is essentially equivalent to    expr?0:1
  274.  
  275.     It is left as an exercise for the reader to show that
  276.  
  277.         if(!p)    is equivalent to        if(p == 0)
  278.  
  279.     "Abbreviations" such as if(p), though perfectly legal, are
  280.     considered by some to be bad style.
  281.  
  282.     See also question 8.2.
  283.  
  284.     References: K&R II Sec. A7.4.7 p. 204; H&S Sec. 5.3 p. 91; ANSI
  285.     Secs. 3.3.3.3, 3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, and
  286.     3.6.5 .
  287.  
  288. 1.8:    If "NULL" and "0" are equivalent, which should I use?
  289.  
  290. A:    Many programmers believe that "NULL" should be used in all
  291.     pointer contexts, as a reminder that the value is to be thought
  292.     of as a pointer.  Others feel that the confusion surrounding
  293.     "NULL" and "0" is only compounded by hiding "0" behind a
  294.     #definition, and prefer to use unadorned "0" instead.  There is
  295.     no one right answer.  C programmers must understand that "NULL"
  296.     and "0" are interchangeable and that an uncast "0" is perfectly
  297.     acceptable in initialization, assignment, and comparison
  298.     contexts.  Any usage of "NULL" (as opposed to "0") should be
  299.     considered a gentle reminder that a pointer is involved;
  300.     programmers should not depend on it (either for their own
  301.     understanding or the compiler's) for distinguishing pointer 0's
  302.     from integer 0's.
  303.  
  304.     NULL should _not_ be used when another kind of 0 is required,
  305.     even though it might work, because doing so sends the wrong
  306.     stylistic message.  (ANSI allows the #definition of NULL to be
  307.     (void *)0, which will not work in non-pointer contexts.)  In
  308.     particular, do not use NULL when the ASCII null character (NUL)
  309.     is desired.  Provide your own definition
  310.  
  311.         #define NUL '\0'
  312.  
  313.     if you must.
  314.  
  315.     References: K&R II Sec. 5.4 p. 102.
  316.  
  317. 1.9:    But wouldn't it be better to use NULL (rather than 0) in case
  318.     the value of NULL changes, perhaps on a machine with nonzero
  319.     null pointers?
  320.  
  321. A:    No.  Although symbolic constants are often used in place of
  322.     numbers because the numbers might change, this is _not_ the
  323.     reason that NULL is used in place of 0.  Once again, the
  324.     language guarantees that source-code 0's (in pointer contexts)
  325.     generate null pointers.  NULL is used only as a stylistic
  326.     convention.
  327.  
  328. 1.10:    I'm confused.  NULL is guaranteed to be 0, but the null pointer
  329.     is not?
  330.  
  331. A:    When the term "null" or "NULL" is casually used, one of several
  332.     things may be meant:
  333.  
  334.     1.    The conceptual null pointer, the abstract language
  335.         concept defined in question 1.1.  It is implemented
  336.         with...
  337.  
  338.     2.    The internal (or run-time) representation of a null
  339.         pointer, which may or may not be all-bits-0 and which
  340.         may be different for different pointer types.  The
  341.         actual values should be of concern only to compiler
  342.         writers.  Authors of C programs never see them, since
  343.         they use...
  344.  
  345.     3.    The source code syntax for null pointers, which is the
  346.         single character "0".  It is often hidden behind...
  347.  
  348.     4.    The NULL macro, which is #defined to be "0" or
  349.         "(void *)0".  Finally, as red herrings, we have...
  350.  
  351.     5.    The ASCII null character (NUL), which does have all bits
  352.         zero, but has no necessary relation to the null pointer
  353.         except in name; and...
  354.  
  355.     6.    The "null string," which is another name for an empty
  356.         string ("").  The term "null string" can be confusing in
  357.         C (and should perhaps be avoided), because it involves a
  358.         null ('\0') character, but not a null pointer, which
  359.         brings us full circle...
  360.  
  361.     This article always uses the phrase "null pointer" (in lower
  362.     case) for sense 1, the character "0" for sense 3, and the
  363.     capitalized word "NULL" for sense 4.
  364.  
  365. 1.11:    Why is there so much confusion surrounding null pointers?  Why
  366.     do these questions come up so often?
  367.  
  368. A:    C programmers traditionally like to know more than they need to
  369.     about the underlying machine implementation.  The fact that null
  370.     pointers are represented both in source code, and internally to
  371.     most machines, as zero invites unwarranted assumptions.  The use
  372.     of a preprocessor macro (NULL) suggests that the value might
  373.     change later, or on some weird machine.  The construct
  374.     "if(p == 0)" is easily misread as calling for conversion of p to
  375.     an integral type, rather than 0 to a pointer type, before the
  376.     comparison.  Finally, the distinction between the several uses
  377.     of the term "null" (listed above) is often overlooked.
  378.  
  379.     One good way to wade out of the confusion is to imagine that C
  380.     had a keyword (perhaps "nil", like Pascal) with which null
  381.     pointers were requested.  The compiler could either turn "nil"
  382.     into the correct type of null pointer, when it could determine
  383.     the type from the source code, or complain when it could not.
  384.     Now, in fact, in C the keyword for a null pointer is not "nil"
  385.     but "0", which works almost as well, except that an uncast "0"
  386.     in a non-pointer context generates an integer zero instead of an
  387.     error message, and if that uncast 0 was supposed to be a null
  388.     pointer, the code may not work.
  389.  
  390. 1.12:    I'm still confused.  I just can't understand all this null
  391.     pointer stuff.
  392.  
  393. A:    Follow these two simple rules:
  394.  
  395.     1.    When you want to refer to a null pointer in source code,
  396.         use "0" or "NULL".
  397.  
  398.     2.    If the usage of "0" or "NULL" is an argument in a
  399.         function call, cast it to the pointer type expected by
  400.         the function being called.
  401.  
  402.     The rest of the discussion has to do with other people's
  403.     misunderstandings, or with the internal representation of null
  404.     pointers (which you shouldn't need to know), or with ANSI C
  405.     refinements.  Understand questions 1.1, 1.2, and 1.3, and
  406.     consider 1.8 and 1.11, and you'll do fine.
  407.  
  408. 1.13:    Given all the confusion surrounding null pointers, wouldn't it
  409.     be easier simply to require them to be represented internally by
  410.     zeroes?
  411.  
  412. A:    If for no other reason, doing so would be ill-advised because it
  413.     would unnecessarily constrain implementations which would
  414.     otherwise naturally represent null pointers by special, nonzero
  415.     bit patterns, particularly when those values would trigger
  416.     automatic hardware traps for invalid accesses.
  417.  
  418.     Besides, what would this requirement really accomplish?  Proper
  419.     understanding of null pointers does not require knowledge of the
  420.     internal representation, whether zero or nonzero.  Assuming that
  421.     null pointers are internally zero does not make any code easier
  422.     to write (except for a certain ill-advised usage of calloc; see
  423.     question 3.13).  Known-zero internal pointers would not obviate
  424.     casts in function calls, because the _size_ of the pointer might
  425.     still be different from that of an int.  (If "nil" were used to
  426.     request null pointers rather than "0," as mentioned in question
  427.     1.11, the urge to assume an internal zero representation would
  428.     not even arise.)
  429.  
  430. 1.14:    Seriously, have any actual machines really used nonzero null
  431.     pointers, or different representations for pointers to different
  432.     types?
  433.  
  434. A:    The Prime 50 series used segment 07777, offset 0 for the null
  435.     pointer, at least for PL/I.  Later models used segment 0, offset
  436.     0 for null pointers in C, necessitating new instructions such as
  437.     TCNP (Test C Null Pointer), evidently as a sop to all the extant
  438.     poorly-written C code which made incorrect assumptions.  Older,
  439.     word-addressed Prime machines were also notorious for requiring
  440.     larger byte pointers (char *'s) than word pointers (int *'s).
  441.  
  442.     The Eclipse MV series from Data General has three
  443.     architecturally supported pointer formats (word, byte, and bit
  444.     pointers), two of which are used by C compilers: byte pointers
  445.     for char * and void *, and word pointers for everything else.
  446.  
  447.     Some Honeywell-Bull mainframes use the bit pattern 06000 for
  448.     (internal) null pointers.
  449.  
  450.     The CDC Cyber 180 Series has 48-bit pointers consisting of a
  451.     ring, segment, and offset.  Most users (in ring 11) have null
  452.     pointers of 0xB00000000000.
  453.  
  454.     The Symbolics Lisp Machine, a tagged architecture, does not even
  455.     have conventional numeric pointers; it uses the pair <NIL, 0>
  456.     (basically a nonexistent <object, offset> handle) as a C null
  457.     pointer.
  458.  
  459.     Depending on the "memory model" in use, 80*86 processors (PC's)
  460.     may use 16 bit data pointers and 32 bit function pointers, or
  461.     vice versa.
  462.  
  463.     The old HP 3000 series computers use a different addressing
  464.     scheme for byte addresses than for word addresses; void and char
  465.     pointers therefore have a different representation than an int
  466.     (structure, etc.) pointer to the same address would have.
  467.  
  468. 1.15:    What does a run-time "null pointer assignment" error mean?  How
  469.     do I track it down?
  470.  
  471. A:    This message, which occurs only under MS-DOS (see, therefore,
  472.     section 16) means that you've written, via an unintialized
  473.     and/or null pointer, to location zero.
  474.  
  475.     A debugger will usually let you set a data breakpoint on
  476.     location 0.  Alternately, you could write a bit of code to copy
  477.     20 or so bytes from location 0 into another buffer, and
  478.     periodically check that it hasn't changed.
  479.  
  480.  
  481. Section 2. Arrays and Pointers
  482.  
  483. 2.1:    I had the definition char a[6] in one source file, and in
  484.     another I declared extern char *a.  Why didn't it work?
  485.  
  486. A:    The declaration extern char *a simply does not match the actual
  487.     definition.  The type "pointer-to-type-T" is not the same as
  488.     "array-of-type-T."  Use extern char a[].
  489.  
  490.     References: CT&P Sec. 3.3 pp. 33-4, Sec. 4.5 pp. 64-5.
  491.  
  492. 2.2:    But I heard that char a[] was identical to char *a.
  493.  
  494. A:    Not at all.  (What you heard has to do with formal parameters to
  495.     functions; see question 2.4.)  Arrays are not pointers.  The
  496.     array declaration "char a[6];" requests that space for six
  497.     characters be set aside, to be known by the name "a."  That is,
  498.     there is a location named "a" at which six characters can sit.
  499.     The pointer declaration "char *p;" on the other hand, requests a
  500.     place which holds a pointer.  The pointer is to be known by the
  501.     name "p," and can point to any char (or contiguous array of
  502.     chars) anywhere.
  503.  
  504.     As usual, a picture is worth a thousand words.  The statements
  505.  
  506.         char a[] = "hello";
  507.         char *p = "world";
  508.  
  509.     would result in data structures which could be represented like
  510.     this:
  511.  
  512.            +---+---+---+---+---+---+
  513.         a: | h | e | l | l | o |\0 |
  514.            +---+---+---+---+---+---+
  515.  
  516.            +-----+     +---+---+---+---+---+---+
  517.         p: |  *======> | w | o | r | l | d |\0 |
  518.            +-----+     +---+---+---+---+---+---+
  519.  
  520.     It is important to realize that a reference like x[3] generates
  521.     different code depending on whether x is an array or a pointer.
  522.     Given the declarations above, when the compiler sees the
  523.     expression a[3], it emits code to start at the location "a,"
  524.     move three past it, and fetch the character there.  When it sees
  525.     the expression p[3], it emits code to start at the location "p,"
  526.     fetch the pointer value there, add three to the pointer, and
  527.     finally fetch the character pointed to.  In the example above,
  528.     both a[3] and p[3] happen to be the character 'l', but the
  529.     compiler gets there differently.  (See also questions 17.19 and
  530.     17.20.)
  531.  
  532. 2.3:    So what is meant by the "equivalence of pointers and arrays" in
  533.     C?
  534.  
  535. A:    Much of the confusion surrounding pointers in C can be traced to
  536.     a misunderstanding of this statement.  Saying that arrays and
  537.     pointers are "equivalent" neither means that they are identical
  538.     nor even interchangeable.
  539.  
  540.     "Equivalence" refers to the following key definition:
  541.  
  542.         An lvalue [see question 2.5] of type array-of-T
  543.         which appears in an expression decays (with
  544.         three exceptions) into a pointer to its first
  545.         element; the type of the resultant pointer is
  546.         pointer-to-T.
  547.  
  548.     (The exceptions are when the array is the operand of a sizeof or
  549.     & operator, or is a literal string initializer for a character
  550.     array.)
  551.  
  552.     As a consequence of this definition, there is no apparent
  553.     difference in the behavior of the "array subscripting" operator
  554.     [] as it applies to arrays and pointers.  In an expression of
  555.     the form a[i], the array reference "a" decays into a pointer,
  556.     following the rule above, and is then subscripted just as would
  557.     be a pointer variable in the expression p[i] (although the
  558.     eventual memory accesses will be different, as explained in
  559.     question 2.2).  In either case, the expression x[i] (where x is
  560.     an array or a pointer) is, by definition, identical to
  561.     *((x)+(i)).
  562.  
  563.     References: K&R I Sec. 5.3 pp. 93-6; K&R II Sec. 5.3 p. 99; H&S
  564.     Sec. 5.4.1 p. 93; ANSI Sec. 3.2.2.1, Sec. 3.3.2.1, Sec. 3.3.6 .
  565.  
  566. 2.4:    Then why are array and pointer declarations interchangeable as
  567.     function formal parameters?
  568.  
  569. A:    Since arrays decay immediately into pointers, an array is never
  570.     actually passed to a function.  As a convenience, any parameter
  571.     declarations which "look like" arrays, e.g.
  572.  
  573.         f(a)
  574.         char a[];
  575.  
  576.     are treated by the compiler as if they were pointers, since that
  577.     is what the function will receive if an array is passed:
  578.  
  579.         f(a)
  580.         char *a;
  581.  
  582.     This conversion holds only within function formal parameter
  583.     declarations, nowhere else.  If this conversion bothers you,
  584.     avoid it; many people have concluded that the confusion it
  585.     causes outweighs the small advantage of having the declaration
  586.     "look like" the call and/or the uses within the function.
  587.  
  588.     References: K&R I Sec. 5.3 p. 95, Sec. A10.1 p. 205; K&R II
  589.     Sec. 5.3 p. 100, Sec. A8.6.3 p. 218, Sec. A10.1 p. 226; H&S
  590.     Sec. 5.4.3 p. 96; ANSI Sec. 3.5.4.3, Sec. 3.7.1, CT&P Sec. 3.3
  591.     pp. 33-4.
  592.  
  593. 2.5:    How can an array be an lvalue, if you can't assign to it?
  594.  
  595. A:    The ANSI C Standard defines a "modifiable lvalue," which an
  596.     array is not.
  597.  
  598.     References: ANSI Sec. 3.2.2.1 p. 37.
  599.  
  600. 2.6:    Why doesn't sizeof properly report the size of an array which is
  601.     a parameter to a function?
  602.  
  603. A:    The sizeof operator reports the size of the pointer parameter
  604.     which the function actually receives (see question 2.4).
  605.  
  606. 2.7:    Someone explained to me that arrays were really just constant
  607.     pointers.
  608.  
  609. A:    This is a bit of an oversimplification.  An array name is
  610.     "constant" in that it cannot be assigned to, but an array is
  611.     _not_ a pointer, as the discussion and pictures in question 2.2
  612.     should make clear.
  613.  
  614. 2.8:    Practically speaking, what is the difference between arrays and
  615.     pointers?
  616.  
  617. A:    Arrays automatically allocate space, but can't be relocated or
  618.     resized.  Pointers must be explicitly assigned to point to
  619.     allocated space (perhaps using malloc), but can be reassigned
  620.     (i.e. pointed at different objects) at will, and have many other
  621.     uses besides serving as the base of blocks of memory.
  622.  
  623.     Due to the so-called equivalence of arrays and pointers (see
  624.     question 2.3), arrays and pointers often seem interchangeable,
  625.     and in particular a pointer to a block of memory assigned by
  626.     malloc is frequently treated (and can be referenced using []
  627.     exactly) as if it were a true array.  (See question 2.14; see
  628.     also question 17.20.)
  629.  
  630. 2.9:    I came across some "joke" code containing the "expression"
  631.     5["abcdef"] .  How can this be legal C?
  632.  
  633. A:    Yes, Virginia, array subscripting is commutative in C.  This
  634.     curious fact follows from the pointer definition of array
  635.     subscripting, namely that a[e] is identical to *((a)+(e)), for
  636.     _any_ expression e and primary expression a, as long as one of
  637.     them is a pointer expression and one is integral.  This
  638.     unsuspected commutativity is often mentioned in C texts as if it
  639.     were something to be proud of, but it finds no useful
  640.     application outside of the Obfuscated C Contest (see question
  641.     17.13).
  642.  
  643.     References: ANSI Rationale Sec. 3.3.2.1 p. 41.
  644.  
  645. 2.10:    My compiler complained when I passed a two-dimensional array to
  646.     a routine expecting a pointer to a pointer.
  647.  
  648. A:    The rule by which arrays decay into pointers is not applied
  649.     recursively.  An array of arrays (i.e. a two-dimensional array
  650.     in C) decays into a pointer to an array, not a pointer to a
  651.     pointer.  Pointers to arrays can be confusing, and must be
  652.     treated carefully.  (The confusion is heightened by the
  653.     existence of incorrect compilers, including some versions of pcc
  654.     and pcc-derived lint's, which improperly accept assignments of
  655.     multi-dimensional arrays to multi-level pointers.)  If you are
  656.     passing a two-dimensional array to a function:
  657.  
  658.         int array[NROWS][NCOLUMNS];
  659.         f(array);
  660.  
  661.     the function's declaration should match:
  662.  
  663.         f(int a[][NCOLUMNS]) {...}
  664.     or
  665.         f(int (*ap)[NCOLUMNS]) {...}   /* ap is a pointer to an array */
  666.  
  667.     In the first declaration, the compiler performs the usual
  668.     implicit parameter rewriting of "array of array" to "pointer to
  669.     array;" in the second form the pointer declaration is explicit.
  670.     Since the called function does not allocate space for the array,
  671.     it does not need to know the overall size, so the number of
  672.     "rows," NROWS, can be omitted.  The "shape" of the array is
  673.     still important, so the "column" dimension NCOLUMNS (and, for 3-
  674.     or more dimensional arrays, the intervening ones) must be
  675.     included.
  676.  
  677.     If a function is already declared as accepting a pointer to a
  678.     pointer, it is probably incorrect to pass a two-dimensional
  679.     array directly to it.
  680.  
  681.     References: K&R I Sec. 5.10 p. 110; K&R II Sec. 5.9 p. 113.
  682.  
  683. 2.11:    How do I write functions which accept 2-dimensional arrays when
  684.     the "width" is not known at compile time?
  685.  
  686. A:    It's not easy.  One way is to pass in a pointer to the [0][0]
  687.     element, along with the two dimensions, and simulate array
  688.     subscripting "by hand:"
  689.  
  690.         f2(aryp, nrows, ncolumns)
  691.         int *aryp;
  692.         int nrows, ncolumns;
  693.         { ... ary[i][j] is really aryp[i * ncolumns + j] ... }
  694.  
  695.     This function could be called with the array from question 2.10
  696.     as
  697.  
  698.         f2(&array[0][0], NROWS, NCOLUMNS);
  699.  
  700.     It must be noted, however, that a program which performs
  701.     multidimensional array subscripting "by hand" in this way is not
  702.     in strict conformance with the ANSI C Standard; the behavior of
  703.     accessing (&array[0][0])[x] is not defined for x > NCOLUMNS.
  704.  
  705.     gcc allows local arrays to be declared having sizes which are
  706.     specified by a function's arguments, but this is a nonstandard
  707.     extension.
  708.  
  709.     See also question 2.15.
  710.  
  711. 2.12:    How do I declare a pointer to an array?
  712.  
  713. A:    Usually, you don't want to.  When people speak casually of a
  714.     pointer to an array, they usually mean a pointer to its first
  715.     element.
  716.  
  717.     Instead of a pointer to an array, consider using a pointer to
  718.     one of the array's elements.  Arrays of type T decay into
  719.     pointers to type T (see question 2.3), which is convenient;
  720.     subscripting or incrementing the resultant pointer accesses the
  721.     individual members of the array.  True pointers to arrays, when
  722.     subscripted or incremented, step over entire arrays, and are
  723.     generally only useful when operating on arrays of arrays, if at
  724.     all.  (See question 2.10 above.)
  725.  
  726.     If you really need to declare a pointer to an entire array, use
  727.     something like "int (*ap)[N];" where N is the size of the array.
  728.     (See also question 10.4.)  If the size of the array is unknown,
  729.     N can be omitted, but the resulting type, "pointer to array of
  730.     unknown size," is useless.
  731.  
  732. 2.13:    Since array references decay to pointers, given
  733.  
  734.         int array[NROWS][NCOLUMNS];
  735.  
  736.     what's the difference between array and &array?
  737.  
  738. A:    Under ANSI/ISO Standard C, &array yields a pointer, of type
  739.     pointer-to-array-of-T, to the entire array (see also question
  740.     2.12).  Under pre-ANSI C, the & in &array generally elicited a
  741.     warning, and was generally ignored.  Under all C compilers, an
  742.     unadorned reference to an array yields a pointer, of type
  743.     pointer-to-T, to the array's first element.  (See also question
  744.     2.3.)
  745.  
  746. 2.14:    How can I dynamically allocate a multidimensional array?
  747.  
  748. A:    It is usually best to allocate an array of pointers, and then
  749.     initialize each pointer to a dynamically-allocated "row."  Here
  750.     is a two-dimensional example:
  751.  
  752.         int **array1 = (int **)malloc(nrows * sizeof(int *));
  753.         for(i = 0; i < nrows; i++)
  754.             array1[i] = (int *)malloc(ncolumns * sizeof(int));
  755.  
  756.     (In "real" code, of course, malloc would be declared correctly,
  757.     and each return value checked.)
  758.  
  759.     You can keep the array's contents contiguous, while making later
  760.     reallocation of individual rows difficult, with a bit of
  761.     explicit pointer arithmetic:
  762.  
  763.         int **array2 = (int **)malloc(nrows * sizeof(int *));
  764.         array2[0] = (int *)malloc(nrows * ncolumns * sizeof(int));
  765.         for(i = 1; i < nrows; i++)
  766.             array2[i] = array2[0] + i * ncolumns;
  767.  
  768.     In either case, the elements of the dynamic array can be
  769.     accessed with normal-looking array subscripts: array[i][j].
  770.  
  771.     If the double indirection implied by the above schemes is for
  772.     some reason unacceptable, you can simulate a two-dimensional
  773.     array with a single, dynamically-allocated one-dimensional
  774.     array:
  775.  
  776.         int *array3 = (int *)malloc(nrows * ncolumns * sizeof(int));
  777.  
  778.     However, you must now perform subscript calculations manually,
  779.     accessing the i,jth element with array3[i * ncolumns + j].  (A
  780.     macro can hide the explicit calculation, but invoking it then
  781.     requires parentheses and commas which don't look exactly like
  782.     multidimensional array subscripts.)
  783.  
  784.     Finally, you can use pointers-to-arrays:
  785.  
  786.         int (*array4)[NCOLUMNS] =
  787.             (int (*)[NCOLUMNS])malloc(nrows * sizeof(*array4));
  788.  
  789.     , but the syntax gets horrific and all but one dimension must be
  790.     known at compile time.
  791.  
  792.     With all of these techniques, you may of course need to remember
  793.     to free the arrays (which may take several steps; see question
  794.     3.9) when they are no longer needed, and you cannot necessarily
  795.     intermix the dynamically-allocated arrays with conventional,
  796.     statically-allocated ones (see question 2.15 below, and also
  797.     question 2.10).
  798.  
  799. 2.15:    How can I use statically- and dynamically-allocated
  800.     multidimensional arrays interchangeably when passing them to
  801.     functions?
  802.  
  803. A:    There is no single perfect method.  Given the declarations
  804.  
  805.         int array[NROWS][NCOLUMNS];
  806.         int **array1;
  807.         int **array2;
  808.         int *array3;
  809.         int (*array4)[NCOLUMNS];
  810.  
  811.     as initialized in the code fragments in questions 2.10 and 2.14,
  812.     and functions declared as
  813.  
  814.         f1(int a[][NCOLUMNS], int m, int n);
  815.         f2(int *aryp, int nrows, int ncolumns);
  816.         f3(int **pp, int m, int n);
  817.  
  818.     (see questions 2.10 and 2.11), the following calls should work
  819.     as expected:
  820.  
  821.         f1(array, NROWS, NCOLUMNS);
  822.         f1(array4, nrows, NCOLUMNS);
  823.         f2(&array[0][0], NROWS, NCOLUMNS);
  824.         f2(*array2, nrows, ncolumns);
  825.         f2(array3, nrows, ncolumns);
  826.         f2(*array4, nrows, NCOLUMNS);
  827.         f3(array1, nrows, ncolumns);
  828.         f3(array2, nrows, ncolumns);
  829.  
  830.     The following two calls would probably work, but involve
  831.     questionable casts, and work only if the dynamic ncolumns
  832.     matches the static NCOLUMNS:
  833.  
  834.         f1((int (*)[NCOLUMNS])(*array2), nrows, ncolumns);
  835.         f1((int (*)[NCOLUMNS])array3, nrows, ncolumns);
  836.  
  837.     It must again be noted that passing &array[0][0] to f2() is not
  838.     strictly conforming; see question 2.11.
  839.  
  840.     If you can understand why all of the above calls work and are
  841.     written as they are, and if you understand why the combinations
  842.     that are not listed would not work, then you have a _very_ good
  843.     understanding of arrays and pointers (and several other areas)
  844.     in C.
  845.  
  846. 2.16:    Here's a neat trick: if I write
  847.  
  848.         int realarray[10];
  849.         int *array = &realarray[-1];
  850.  
  851.     I can treat "array" as if it were a 1-based array.
  852.  
  853. A:    Although this technique is attractive (and was used in old
  854.     editions of the book Numerical Recipes in C), it does not
  855.     conform to the C standards.  Pointer arithmetic is defined only
  856.     as long as the pointer points within the same allocated block of
  857.     memory, or to the imaginary "terminating" element one past it;
  858.     otherwise, the behavior is undefined, _even if the pointer is
  859.     not dereferenced_.  The code above could fail if, while
  860.     subtracting the offset, an illegal address were generated
  861.     (perhaps because the address tried to "wrap around" past the
  862.     beginning of some memory segment).
  863.  
  864.     References: ANSI Sec. 3.3.6 p. 48, Rationale Sec. 3.2.2.3 p. 38;
  865.     K&R II Sec. 5.3 p. 100, Sec. 5.4 pp. 102-3, Sec. A7.7 pp. 205-6.
  866.  
  867. 2.17:    I passed a pointer to a function which initialized it:
  868.  
  869.         ...
  870.         int *ip;
  871.         f(ip);
  872.         ...
  873.  
  874.         void f(ip)
  875.         int *ip;
  876.         {
  877.             static int dummy = 5;
  878.             ip = &dummy;
  879.         }
  880.  
  881.     , but the pointer in the caller was unchanged.
  882.  
  883. A:    Did the function try to initialize the pointer itself, or just
  884.     what it pointed to?  Remember that arguments in C are passed by
  885.     value.  The called function altered only the passed copy of the
  886.     pointer.  You'll either want to pass the address of the pointer
  887.     (the function will end up accepting a pointer-to-a-pointer), or
  888.     have the function return the pointer.
  889.  
  890. 2.18:    I have a char * pointer that happens to point to some ints, and
  891.     I want to step it over them.  Why doesn't
  892.  
  893.         ((int *)p)++;
  894.  
  895.     work?
  896.  
  897. A:    In C, a cast operator does not mean "pretend these bits have a
  898.     different type, and treat them accordingly;" it is a conversion
  899.     operator, and by definition it yields an rvalue, which cannot be
  900.     assigned to, or incremented with ++.  (It is an anomaly in pcc-
  901.     derived compilers, and an extension in gcc, that expressions
  902.     such as the above are ever accepted.)  Say what you mean: use
  903.  
  904.         p = (char *)((int *)p + 1);
  905.  
  906.     , or simply
  907.  
  908.         p += sizeof(int);
  909.  
  910.     References: ANSI Sec. 3.3.4, Rationale Sec. 3.3.2.4 p. 43.
  911.  
  912. 2.19:    Can I use a void ** pointer to pass a generic pointer to a
  913.     function by reference?
  914.  
  915. A:    Not portably.  There is no generic pointer-to-pointer type in C.
  916.     void * acts as a generic pointer only because conversions are
  917.     applied automatically when other pointer types are assigned to
  918.     and from void *'s; these conversions cannot be performed (the
  919.     correct underlying pointer type is not known) if an attempt is
  920.     made to indirect upon a void ** value which points at something
  921.     other than a void *.
  922.  
  923.  
  924. Section 3. Memory Allocation
  925.  
  926. 3.1:    Why doesn't this fragment work?
  927.  
  928.         char *answer;
  929.         printf("Type something:\n");
  930.         gets(answer);
  931.         printf("You typed \"%s\"\n", answer);
  932.  
  933. A:    The pointer variable "answer," which is handed to the gets
  934.     function as the location into which the response should be
  935.     stored, has not been set to point to any valid storage.  That
  936.     is, we cannot say where the pointer "answer" points.  (Since
  937.     local variables are not initialized, and typically contain
  938.     garbage, it is not even guaranteed that "answer" starts out as a
  939.     null pointer.  See question 17.1.)
  940.  
  941.     The simplest way to correct the question-asking program is to
  942.     use a local array, instead of a pointer, and let the compiler
  943.     worry about allocation:
  944.  
  945.         #include <string.h>
  946.  
  947.         char answer[100], *p;
  948.         printf("Type something:\n");
  949.         fgets(answer, sizeof(answer), stdin);
  950.         if((p = strchr(answer, '\n')) != NULL)
  951.             *p = '\0';
  952.         printf("You typed \"%s\"\n", answer);
  953.  
  954.     Note that this example also uses fgets() instead of gets()
  955.     (always a good idea; see question 11.6), allowing the size of
  956.     the array to be specified, so that the end of the array will not
  957.     be overwritten if the user types an overly-long line.
  958.     (Unfortunately for this example, fgets() does not automatically
  959.     delete the trailing \n, as gets() would.)  It would also be
  960.     possible to use malloc() to allocate the answer buffer.
  961.  
  962. 3.2:    I can't get strcat to work.  I tried
  963.  
  964.         char *s1 = "Hello, ";
  965.         char *s2 = "world!";
  966.         char *s3 = strcat(s1, s2);
  967.  
  968.     but I got strange results.
  969.  
  970. A:    Again, the problem is that space for the concatenated result is
  971.     not properly allocated.  C does not provide an automatically-
  972.     managed string type.  C compilers only allocate memory for
  973.     objects explicitly mentioned in the source code (in the case of
  974.     "strings," this includes character arrays and string literals).
  975.     The programmer must arrange (explicitly) for sufficient space
  976.     for the results of run-time operations such as string
  977.     concatenation, typically by declaring arrays, or by calling
  978.     malloc.  (See also question 17.20.)
  979.  
  980.     strcat performs no allocation; the second string is appended to
  981.     the first one, in place.  Therefore, one fix would be to declare
  982.     the first string as an array with sufficient space:
  983.  
  984.         char s1[20] = "Hello, ";
  985.  
  986.     Since strcat returns the value of its first argument (s1, in
  987.     this case), the s3 variable is superfluous.
  988.  
  989.     References: CT&P Sec. 3.2 p. 32.
  990.  
  991. 3.3:    But the man page for strcat says that it takes two char *'s as
  992.     arguments.  How am I supposed to know to allocate things?
  993.  
  994. A:    In general, when using pointers you _always_ have to consider
  995.     memory allocation, at least to make sure that the compiler is
  996.     doing it for you.  If a library routine's documentation does not
  997.     explicitly mention allocation, it is usually the caller's
  998.     problem.
  999.  
  1000.     The Synopsis section at the top of a Unix-style man page can be
  1001.     misleading.  The code fragments presented there are closer to
  1002.     the function definition used by the call's implementor than the
  1003.     invocation used by the caller.  In particular, many routines
  1004.     which accept pointers (e.g. to structs or strings), are usually
  1005.     called with the address of some object (a struct, or an array --
  1006.     see questions 2.3 and 2.4.)  Another common example is stat().
  1007.  
  1008. 3.4:    I have a function that is supposed to return a string, but when
  1009.     it returns to its caller, the returned string is garbage.
  1010.  
  1011. A:    Make sure that the memory to which the function returns a
  1012.     pointer is correctly allocated.  The returned pointer should be
  1013.     to a statically-allocated buffer, or to a buffer passed in by
  1014.     the caller, or to memory obtained with malloc(), but _not_ to a
  1015.     local (auto) array.  In other words, never do something like
  1016.  
  1017.         char *f()
  1018.         {
  1019.             char buf[10];
  1020.             /* ... */
  1021.             return buf;
  1022.         }
  1023.  
  1024.     One fix (which is imperfect, especially if f() is called
  1025.     recursively, or if several of its return values are needed
  1026.     simultaneously) would to to declare the buffer as
  1027.  
  1028.             static char buf[10];
  1029.  
  1030.     See also question 17.5.
  1031.  
  1032. 3.5:    Why does some code carefully cast the values returned by malloc
  1033.     to the pointer type being allocated?
  1034.  
  1035. A:    Before ANSI/ISO Standard C introduced the void * generic pointer
  1036.     type, these casts were typically required to silence warnings
  1037.     about assignment between incompatible pointer types.  (Under
  1038.     ANSI/ISO Standard C, these casts are not required.)
  1039.  
  1040. 3.6:    You can't use dynamically-allocated memory after you free it,
  1041.     can you?
  1042.  
  1043. A:    No.  Some early documentation for malloc stated that the
  1044.     contents of freed memory was "left undisturbed;" this ill-
  1045.     advised guarantee was never universal and is not required by
  1046.     ANSI.
  1047.  
  1048.     Few programmers would use the contents of freed memory
  1049.     deliberately, but it is easy to do so accidentally.  Consider
  1050.     the following (correct) code for freeing a singly-linked list:
  1051.  
  1052.         struct list *listp, *nextp;
  1053.         for(listp = base; listp != NULL; listp = nextp) {
  1054.             nextp = listp->next;
  1055.             free((char *)listp);
  1056.         }
  1057.  
  1058.     and notice what would happen if the more-obvious loop iteration
  1059.     expression listp = listp->next were used, without the temporary
  1060.     nextp pointer.
  1061.  
  1062.     References: ANSI Rationale Sec. 4.10.3.2 p. 102; CT&P Sec. 7.10
  1063.     p. 95.
  1064.  
  1065. 3.7:    How does free() know how many bytes to free?
  1066.  
  1067. A:    The malloc/free package remembers the size of each block it
  1068.     allocates and returns, so it is not necessary to remind it of
  1069.     the size when freeing.
  1070.  
  1071. 3.8:    So can I query the malloc package to find out how big an
  1072.     allocated block is?
  1073.  
  1074. A:    Not portably.
  1075.  
  1076. 3.9:    I'm allocating structures which contain pointers to other
  1077.     dynamically-allocated objects.  When I free a structure, do I
  1078.     have to free each subsidiary pointer first?
  1079.  
  1080. A:    Yes.  In general, you must arrange that each pointer returned
  1081.     from malloc be individually passed to free, exactly once (if it
  1082.     is freed at all).
  1083.  
  1084. 3.10:    I have a program which mallocs but then frees a lot of memory,
  1085.     but memory usage (as reported by ps) doesn't seem to go back
  1086.     down.
  1087.  
  1088. A:    Most implementations of malloc/free do not return freed memory
  1089.     to the operating system (if there is one), but merely make it
  1090.     available for future malloc calls within the same process.
  1091.  
  1092. 3.11:    Must I free allocated memory before the program exits?
  1093.  
  1094. A:    You shouldn't have to.  A real operating system definitively
  1095.     reclaims all memory when a program exits.  Nevertheless, some
  1096.     personal computers are said not to reliably recover memory, and
  1097.     all that can be inferred from the ANSI/ISO C Standard is that it
  1098.     is a "quality of implementation issue."
  1099.  
  1100.     References: ANSI Sec. 4.10.3.2 .
  1101.  
  1102. 3.12:    Is it legal to pass a null pointer as the first argument to
  1103.     realloc()?  Why would you want to?
  1104.  
  1105. A:    ANSI C sanctions this usage (and the related realloc(..., 0),
  1106.     which frees), but several earlier implementations do not support
  1107.     it, so it is not widely portable.  Passing an initially-null
  1108.     pointer to realloc can make it easier to write a self-starting
  1109.     incremental allocation algorithm.
  1110.  
  1111.     References: ANSI Sec. 4.10.3.4 .
  1112.  
  1113. 3.13:    What is the difference between calloc and malloc?  Is it safe to
  1114.     use calloc's zero-fill guarantee for pointer and floating-point
  1115.     values?  Does free work on memory allocated with calloc, or do
  1116.     you need a cfree?
  1117.  
  1118. A:    calloc(m, n) is essentially equivalent to
  1119.  
  1120.         p = malloc(m * n);
  1121.         memset(p, 0, m * n);
  1122.  
  1123.     The zero fill is all-bits-zero, and does not therefore guarantee
  1124.     useful zero values for pointers (see section 1 of this list) or
  1125.     floating-point values.  free can (and should) be used to free
  1126.     the memory allocated by calloc.
  1127.  
  1128.     References: ANSI Secs. 4.10.3 to 4.10.3.2 .
  1129.  
  1130. 3.14:    What is alloca and why is its use discouraged?
  1131.  
  1132. A:    alloca allocates memory which is automatically freed when the
  1133.     function which called alloca returns.  That is, memory allocated
  1134.     with alloca is local to a particular function's "stack frame" or
  1135.     context.
  1136.  
  1137.     alloca cannot be written portably, and is difficult to implement
  1138.     on machines without a stack.  Its use is problematical (and the
  1139.     obvious implementation on a stack-based machine fails) when its
  1140.     return value is passed directly to another function, as in
  1141.     fgets(alloca(100), 100, stdin).
  1142.  
  1143.     For these reasons, alloca cannot be used in programs which must
  1144.     be widely portable, no matter how useful it might be.
  1145.  
  1146.     References: ANSI Rationale Sec. 4.10.3 p. 102.
  1147.  
  1148.  
  1149. Section 4. Expressions
  1150.  
  1151. 4.1:    Why doesn't this code:
  1152.  
  1153.         a[i] = i++;
  1154.  
  1155.     work?
  1156.  
  1157. A:    The subexpression i++ causes a side effect -- it modifies i's
  1158.     value -- which leads to undefined behavior if i is also
  1159.     referenced elsewhere in the same expression.  (Note that
  1160.     although the language in K&R suggests that the behavior of this
  1161.     expression is unspecified, the ANSI/ISO C Standard makes the
  1162.     stronger statement that it is undefined -- see question 5.23.)
  1163.  
  1164.     References: ANSI Sec. 3.3 p. 39.
  1165.  
  1166. 4.2:    Under my compiler, the code
  1167.  
  1168.         int i = 7;
  1169.         printf("%d\n", i++ * i++);
  1170.  
  1171.     prints 49.  Regardless of the order of evaluation, shouldn't it
  1172.     print 56?
  1173.  
  1174. A:    Although the postincrement and postdecrement operators ++ and --
  1175.     perform the operations after yielding the former value, the
  1176.     implication of "after" is often misunderstood.  It is _not_
  1177.     guaranteed that the operation is performed immediately after
  1178.     giving up the previous value and before any other part of the
  1179.     expression is evaluated.  It is merely guaranteed that the
  1180.     update will be performed sometime before the expression is
  1181.     considered "finished" (before the next "sequence point," in ANSI
  1182.     C's terminology).  In the example, the compiler chose to
  1183.     multiply the previous value by itself and to perform both
  1184.     increments afterwards.
  1185.  
  1186.     The behavior of code which contains multiple, ambiguous side
  1187.     effects has always been undefined (see question 5.23).  Don't
  1188.     even try to find out how your compiler implements such things
  1189.     (contrary to the ill-advised exercises in many C textbooks); as
  1190.     K&R wisely point out, "if you don't know _how_ they are done on
  1191.     various machines, that innocence may help to protect you."
  1192.  
  1193.     References: K&R I Sec. 2.12 p. 50; K&R II Sec. 2.12 p. 54; ANSI
  1194.     Sec. 3.3 p. 39; CT&P Sec. 3.7 p. 47; PCS Sec. 9.5 pp. 120-1.
  1195.     (Ignore H&S Sec. 7.12 pp. 190-1, which is obsolete.)
  1196.  
  1197. 4.3:    I've experimented with the code
  1198.  
  1199.         int i = 2;
  1200.         i = i++;
  1201.  
  1202.     on several compilers.  Some gave i the value 2, some gave 3, but
  1203.     one gave 4.  I know the behavior is undefined, but how could it
  1204.     give 4?
  1205.  
  1206. A:    Undefined behavior means _anything_ can happen.  See question
  1207.     5.23.
  1208.  
  1209. 4.4:    People keep saying the behavior is undefined, but I just tried
  1210.     it on an ANSI-conforming compiler, and got the results I
  1211.     expected.
  1212.  
  1213. A:    A compiler may do anything it likes when faced with undefined
  1214.     behavior (and, within limits, with implementation-defined and
  1215.     unspecified behavior), including doing what you expect.  It's
  1216.     unwise to depend on it, though.  See also question 5.18.
  1217.  
  1218. 4.5:    Can I use explicit parentheses to force the order of evaluation
  1219.     I want?  Even if I don't, doesn't precedence dictate it?
  1220.  
  1221. A:    Operator precedence and explicit parentheses impose only a
  1222.     partial ordering on the evaluation of an expression.  Consider
  1223.     the expression
  1224.  
  1225.         f() + g() * h()
  1226.  
  1227.     -- although we know that the multiplication will happen before
  1228.     the addition, there is no telling which of the three functions
  1229.     will be called first.
  1230.  
  1231. 4.6:    But what about the &&, ||, and comma operators?
  1232.     I see code like "if((c = getchar()) == EOF || c == '\n')" ...
  1233.  
  1234. A:    There is a special exception for those operators, (as well as
  1235.     the ?: operator); each of them does imply a sequence point (i.e.
  1236.     left-to-right evaluation is guaranteed).  Any book on C should
  1237.     make this clear.
  1238.  
  1239.     References: K&R I Sec. 2.6 p. 38, Secs. A7.11-12 pp. 190-1;
  1240.     K&R II Sec. 2.6 p. 41, Secs. A7.14-15 pp. 207-8; ANSI
  1241.     Secs. 3.3.13 p. 52, 3.3.14 p. 52, 3.3.15 p. 53, 3.3.17 p. 55,
  1242.     CT&P Sec. 3.7 pp. 46-7.
  1243.  
  1244. 4.7:    If I'm not using the value of the expression, should I use i++
  1245.     or ++i to increment a variable?
  1246.  
  1247. A:    Since the two forms differ only in the value yielded, they are
  1248.     entirely equivalent when only their side effect is needed.
  1249.  
  1250. 4.8:    Why doesn't the code
  1251.  
  1252.         int a = 1000, b = 1000;
  1253.         long int c = a * b;
  1254.  
  1255.     work?
  1256.  
  1257. A:    Under C's integral promotion rules, the multiplication is
  1258.     carried out using int arithmetic, and the result may overflow
  1259.     and/or be truncated before being assigned to the long int left-
  1260.     hand-side.  Use an explicit cast to force long arithmetic:
  1261.  
  1262.         long int c = (long int)a * b;
  1263.  
  1264.     Note that the code (long int)(a * b) would _not_ have the
  1265.     desired effect.
  1266.  
  1267.  
  1268. Section 5. ANSI C
  1269.  
  1270. 5.1:    What is the "ANSI C Standard?"
  1271.  
  1272. A:    In 1983, the American National Standards Institute (ANSI)
  1273.     commissioned a committee, X3J11, to standardize the C language.
  1274.     After a long, arduous process, including several widespread
  1275.     public reviews, the committee's work was finally ratified as ANS
  1276.     X3.159-1989, on December 14, 1989, and published in the spring
  1277.     of 1990.  For the most part, ANSI C standardizes existing
  1278.     practice, with a few additions from C++ (most notably function
  1279.     prototypes) and support for multinational character sets
  1280.     (including the much-lambasted trigraph sequences).  The ANSI C
  1281.     standard also formalizes the C run-time library support
  1282.     routines.
  1283.  
  1284.     The published Standard includes a "Rationale," which explains
  1285.     many of its decisions, and discusses a number of subtle points,
  1286.     including several of those covered here.  (The Rationale is "not
  1287.     part of ANSI Standard X3.159-1989, but is included for
  1288.     information only.")
  1289.  
  1290.     The Standard has been adopted as an international standard,
  1291.     ISO/IEC 9899:1990, although the sections are numbered
  1292.     differently (briefly, ANSI sections 2 through 4 correspond
  1293.     roughly to ISO sections 5 through 7), and the Rationale is
  1294.     currently not included.
  1295.  
  1296. 5.2:    How can I get a copy of the Standard?
  1297.  
  1298. A:    ANSI X3.159 has been officially superseded by ISO 9899.  Copies
  1299.     are available in the United States from
  1300.  
  1301.         American National Standards Institute
  1302.         11 W. 42nd St., 13th floor
  1303.         New York, NY  10036  USA
  1304.         (+1) 212 642 4900
  1305.  
  1306.     or
  1307.  
  1308.         Global Engineering Documents
  1309.         2805 McGaw Avenue
  1310.         Irvine, CA  92714  USA
  1311.         (+1) 714 261 1455
  1312.         (800) 854 7179  (U.S. & Canada)
  1313.  
  1314.     In other countries, contact the appropriate national standards
  1315.     body, or ISO in Geneva at:
  1316.  
  1317.         ISO Sales
  1318.         Case Postale 56
  1319.         CH-1211 Geneve 20
  1320.         Switzerland
  1321.  
  1322.     The cost is $130.00 from ANSI or $162.50 from Global.  Copies of
  1323.     the original X3.159 (including the Rationale) are still
  1324.     available at $205.00 from ANSI or $200.50 from Global.  Note
  1325.     that ANSI derives revenues to support its operations from the
  1326.     sale of printed standards, so electronic copies are _not_
  1327.     available.
  1328.  
  1329.     The mistitled _Annotated ANSI C Standard_, with annotations by
  1330.     Herbert Schildt, contains the full text of ISO 9899; it is
  1331.     published by Osborne/McGraw-Hill, ISBN 0-07-881952-0, and sells
  1332.     in the U.S. for approximately $40.  (It has been suggested that
  1333.     the price differential between this work and the official
  1334.     standard reflects the value of the annotations.)
  1335.  
  1336.     The text of the Rationale (not the full Standard) is now
  1337.     available for anonymous ftp from ftp.uu.net (see question 17.12)
  1338.     in directory doc/standards/ansi/X3.159-1989 .  The Rationale has
  1339.     also been printed by Silicon Press, ISBN 0-929306-07-4.
  1340.  
  1341. 5.3:    Does anyone have a tool for converting old-style C programs to
  1342.     ANSI C, or vice versa, or for automatically generating
  1343.     prototypes?
  1344.  
  1345. A:    Two programs, protoize and unprotoize, convert back and forth
  1346.     between prototyped and "old style" function definitions and
  1347.     declarations.  (These programs do _not_ handle full-blown
  1348.     translation between "Classic" C and ANSI C.)  These programs
  1349.     were once patches to the FSF GNU C compiler, gcc, but are now
  1350.     part of the main gcc distribution; look in pub/gnu at
  1351.     prep.ai.mit.edu (18.71.0.38), or at several other FSF archive
  1352.     sites.
  1353.  
  1354.     The unproto program (/pub/unix/unproto5.shar.Z on
  1355.     ftp.win.tue.nl) is a filter which sits between the preprocessor
  1356.     and the next compiler pass, converting most of ANSI C to
  1357.     traditional C on-the-fly.
  1358.  
  1359.     The GNU GhostScript package comes with a little program called
  1360.     ansi2knr.
  1361.  
  1362.     Several prototype generators exist, many as modifications to
  1363.     lint.  Version 3 of CPROTO was posted to comp.sources.misc in
  1364.     March, 1992.  There is another program called "cextract."  See
  1365.     also question 17.12.
  1366.  
  1367.     Finally, are you sure you really need to convert lots of old
  1368.     code to ANSI C?  The old-style function syntax is still
  1369.     acceptable.
  1370.  
  1371. 5.4:    I'm trying to use the ANSI "stringizing" preprocessing operator
  1372.     # to insert the value of a symbolic constant into a message, but
  1373.     it keeps stringizing the macro's name rather than its value.
  1374.  
  1375. A:    You must use something like the following two-step procedure to
  1376.     force the macro to be expanded as well as stringized:
  1377.  
  1378.         #define str(x) #x
  1379.         #define xstr(x) str(x)
  1380.         #define OP plus
  1381.         char *opname = xstr(OP);
  1382.  
  1383.     This sets opname to "plus" rather than "OP".
  1384.  
  1385.     An equivalent circumlocution is necessary with the token-pasting
  1386.     operator ## when the values (rather than the names) of two
  1387.     macros are to be concatenated.
  1388.  
  1389.     References: ANSI Sec. 3.8.3.2, Sec. 3.8.3.5 example p. 93.
  1390.  
  1391. 5.5:    I don't understand why I can't use const values in initializers
  1392.     and array dimensions, as in
  1393.  
  1394.         const int n = 5;
  1395.         int a[n];
  1396.  
  1397. A:    The const qualifier really means "read-only;" an object so
  1398.     qualified is a normal run-time object which cannot (normally) be
  1399.     assigned to.  The value of a const-qualified object is therefore
  1400.     _not_ a constant expression in the full sense of the term.  (C
  1401.     is unlike C++ in this regard.)  When you need a true compile-
  1402.     time constant, use a preprocessor #define.
  1403.  
  1404.     References: ANSI Sec. 3.4 .
  1405.  
  1406. 5.6:    What's the difference between "char const *p" and
  1407.     "char * const p"?
  1408.  
  1409. A:    "char const *p" is a pointer to a constant character (you can't
  1410.     change the character); "char * const p" is a constant pointer to
  1411.     a (variable) character (i.e. you can't change the pointer).
  1412.     (Read these "inside out" to understand them.  See question
  1413.     10.4.)
  1414.  
  1415.     References: ANSI Sec. 3.5.4.1 .
  1416.  
  1417. 5.7:    Why can't I pass a char ** to a function which expects a
  1418.     const char **?
  1419.  
  1420. A:    You can use a pointer-to-T (for any type T) where a pointer-to-
  1421.     const-T is expected, but the rule (an explicit exception) which
  1422.     permits slight mismatches in qualified pointer types is not
  1423.     applied recursively, but only at the top level.
  1424.  
  1425.     You must use explicit casts (e.g. (const char **) in this case)
  1426.     when assigning (or passing) pointers which have qualifier
  1427.     mismatches at other than the first level of indirection.
  1428.  
  1429.     References: ANSI Sec. 3.1.2.6 p. 26, Sec. 3.3.16.1 p. 54,
  1430.     Sec. 3.5.3 p. 65.
  1431.  
  1432. 5.8:    My ANSI compiler complains about a mismatch when it sees
  1433.  
  1434.         extern int func(float);
  1435.  
  1436.         int func(x)
  1437.         float x;
  1438.         {...
  1439.  
  1440. A:    You have mixed the new-style prototype declaration
  1441.     "extern int func(float);" with the old-style definition
  1442.     "int func(x) float x;".  It is usually safe to mix the two
  1443.     styles (see question 5.9), but not in this case.  Old C (and
  1444.     ANSI C, in the absence of prototypes, and in variable-length
  1445.     argument lists) "widens" certain arguments when they are passed
  1446.     to functions.  floats are promoted to double, and characters and
  1447.     short integers are promoted to ints.  (For old-style function
  1448.     definitions, the values are automatically converted back to the
  1449.     corresponding narrower types within the body of the called
  1450.     function, if they are declared that way there.)
  1451.  
  1452.     This problem can be fixed either by using new-style syntax
  1453.     consistently in the definition:
  1454.  
  1455.         int func(float x) { ... }
  1456.  
  1457.     or by changing the new-style prototype declaration to match the
  1458.     old-style definition:
  1459.  
  1460.         extern int func(double);
  1461.  
  1462.     (In this case, it would be clearest to change the old-style
  1463.     definition to use double as well, as long as the address of that
  1464.     parameter is not taken.)
  1465.  
  1466.     It may also be safer to avoid "narrow" (char, short int, and
  1467.     float) function arguments and return types.
  1468.  
  1469.     References: ANSI Sec. 3.3.2.2 .
  1470.  
  1471. 5.9:    Can you mix old-style and new-style function syntax?
  1472.  
  1473. A:    Doing so is perfectly legal, as long as you're careful (see
  1474.     especially question 5.8).  Note however that old-style syntax is
  1475.     marked as obsolescent, and support for it may be removed some
  1476.     day.
  1477.  
  1478.     References: ANSI Secs. 3.7.1, 3.9.5 .
  1479.  
  1480. 5.10:    Why does the declaration
  1481.  
  1482.         extern f(struct x {int s;} *p);
  1483.  
  1484.     give me an obscure warning message about "struct x introduced in
  1485.     prototype scope"?
  1486.  
  1487. A:    In a quirk of C's normal block scoping rules, a struct declared
  1488.     only within a prototype cannot be compatible with other structs
  1489.     declared in the same source file, nor can the struct tag be used
  1490.     later as you'd expect (it goes out of scope at the end of the
  1491.     prototype).
  1492.  
  1493.     To resolve the problem, precede the prototype with the vacuous-
  1494.     looking declaration
  1495.  
  1496.         struct x;
  1497.  
  1498.     , which will reserve a place at file scope for struct x's
  1499.     definition, which will be completed by the struct declaration
  1500.     within the prototype.
  1501.  
  1502.     References: ANSI Sec. 3.1.2.1 p. 21, Sec. 3.1.2.6 p. 26,
  1503.     Sec. 3.5.2.3 p. 63.
  1504.  
  1505. 5.11:    I'm getting strange syntax errors inside code which I've
  1506.     #ifdeffed out.
  1507.  
  1508. A:    Under ANSI C, the text inside a "turned off" #if, #ifdef, or
  1509.     #ifndef must still consist of "valid preprocessing tokens."
  1510.     This means that there must be no unterminated comments or quotes
  1511.     (note particularly that an apostrophe within a contracted word
  1512.     could look like the beginning of a character constant), and no
  1513.     newlines inside quotes.  Therefore, natural-language comments
  1514.     and pseudocode should always be written between the "official"
  1515.     comment delimiters /* and */.  (But see also question 17.14, and
  1516.     6.7.)
  1517.  
  1518.     References: ANSI Sec. 2.1.1.2 p. 6, Sec. 3.1 p. 19 line 37.
  1519.  
  1520. 5.12:    Can I declare main as void, to shut off these annoying "main
  1521.     returns no value" messages?  (I'm calling exit(), so main
  1522.     doesn't return.)
  1523.  
  1524. A:    No.  main must be declared as returning an int, and as taking
  1525.     either zero or two arguments (of the appropriate type).  If
  1526.     you're calling exit() but still getting warnings, you'll have to
  1527.     insert a redundant return statement (or use some kind of
  1528.     "notreached" directive, if available).
  1529.  
  1530.     Declaring a function as void does not merely silence warnings;
  1531.     it may also result in a different function call/return sequence,
  1532.     incompatible with what the caller (in main's case, the C run-
  1533.     time startup code) expects.
  1534.  
  1535.     References: ANSI Sec. 2.1.2.2.1 pp. 7-8.
  1536.  
  1537. 5.13:    Is exit(status) truly equivalent to returning status from main?
  1538.  
  1539. A:    Formally, yes, although discrepancies arise under a few older,
  1540.     nonconforming systems, or if data local to main() might be needed
  1541.     during cleanup (due perhaps to a setbuf or atexit call), or if
  1542.     main() is called recursively.
  1543.  
  1544.     References: ANSI Sec. 2.1.2.2.3 p. 8.
  1545.  
  1546. 5.14:    Why does the ANSI Standard not guarantee more than six monocase
  1547.     characters of external identifier significance?
  1548.  
  1549. A:    The problem is older linkers which are neither under the control
  1550.     of the ANSI standard nor the C compiler developers on the
  1551.     systems which have them.  The limitation is only that
  1552.     identifiers be _significant_ in the first six characters, not
  1553.     that they be restricted to six characters in length.  This
  1554.     limitation is annoying, but certainly not unbearable, and is
  1555.     marked in the Standard as "obsolescent," i.e. a future revision
  1556.     will likely relax it.
  1557.  
  1558.     This concession to current, restrictive linkers really had to be
  1559.     made, no matter how vehemently some people oppose it.  (The
  1560.     Rationale notes that its retention was "most painful.")  If you
  1561.     disagree, or have thought of a trick by which a compiler
  1562.     burdened with a restrictive linker could present the C
  1563.     programmer with the appearance of more significance in external
  1564.     identifiers, read the excellently-worded section 3.1.2 in the
  1565.     X3.159 Rationale (see question 5.1), which discusses several
  1566.     such schemes and explains why they could not be mandated.
  1567.  
  1568.     References: ANSI Sec. 3.1.2 p. 21, Sec. 3.9.1 p. 96, Rationale
  1569.     Sec. 3.1.2 pp. 19-21.
  1570.  
  1571. 5.15:    What is the difference between memcpy and memmove?
  1572.  
  1573. A:    memmove offers guaranteed behavior if the source and destination
  1574.     arguments overlap.  memcpy makes no such guarantee, and may
  1575.     therefore be more efficiently implementable.  When in doubt,
  1576.     it's safer to use memmove.
  1577.  
  1578.     References: ANSI Secs. 4.11.2.1, 4.11.2.2, Rationale
  1579.     Sec. 4.11.2 .
  1580.  
  1581. 5.16:    My compiler is rejecting the simplest possible test programs,
  1582.     with all kinds of syntax errors.
  1583.  
  1584. A:    Perhaps it is a pre-ANSI compiler, unable to accept function
  1585.     prototypes and the like.  See also questions 5.17 and 17.2.
  1586.  
  1587. 5.17:    Why are some ANSI/ISO Standard library routines showing up as
  1588.     undefined, even though I've got an ANSI compiler?
  1589.  
  1590. A:    It's not unusual to have a compiler available which accepts ANSI
  1591.     syntax, but not to have ANSI-compatible header files or run-time
  1592.     libraries installed.  See also questions 5.16 and 17.2.
  1593.  
  1594. 5.18:    Why won't the Frobozz Magic C Compiler, which claims to be ANSI
  1595.     compliant, accept this code?  I know that the code is ANSI,
  1596.     because gcc accepts it.
  1597.  
  1598. A:    Most compilers support a few non-Standard extensions, gcc more
  1599.     so than most.  Are you sure that the code being rejected doesn't
  1600.     rely on such an extension?  It is usually a bad idea to perform
  1601.     experiments with a particular compiler to determine properties
  1602.     of a language; the applicable standard may permit variations, or
  1603.     the compiler may be wrong.  See also question 4.4.
  1604.  
  1605. 5.19:    Why can't I perform arithmetic on a void * pointer?
  1606.  
  1607. A:    The compiler doesn't know the size of the pointed-to objects.
  1608.     Before performing arithmetic, cast the pointer either to char *
  1609.     or to the type you're trying to manipulate (but see question
  1610.     2.18).
  1611.  
  1612. 5.20:    Is char a[3] = "abc"; legal?  What does it mean?
  1613.  
  1614. A:    It is legal in ANSI C (and perhaps in a few pre-ANSI systems),
  1615.     though questionably useful.  It declares an array of size three,
  1616.     initialized with the three characters 'a', 'b', and 'c', without
  1617.     the usual terminating '\0' character; the array is therefore not
  1618.     a true C string and cannot be used with strcpy, printf %s, etc.
  1619.  
  1620.     References: ANSI Sec. 3.5.7 pp. 72-3.
  1621.  
  1622. 5.21:    What are #pragmas and what are they good for?
  1623.  
  1624. A:    The #pragma directive provides a single, well-defined "escape
  1625.     hatch" which can be used for all sorts of implementation-
  1626.     specific controls and extensions: source listing control,
  1627.     structure packing, warning suppression (like the old lint
  1628.     /* NOTREACHED */ comments), etc.
  1629.  
  1630.     References: ANSI Sec. 3.8.6 .
  1631.  
  1632. 5.22:    What does "#pragma once" mean?  I found it in some header files.
  1633.  
  1634. A:    It is an extension implemented by some preprocessors to help
  1635.     make header files idempotent; it is essentially equivalent to
  1636.     the #ifndef trick mentioned in question 6.4.
  1637.  
  1638. 5.23:    People seem to make a point of distinguishing between
  1639.     implementation-defined, unspecified, and undefined behavior.
  1640.     What's the difference?
  1641.  
  1642. A:    Briefly: implementation-defined means that an implementation
  1643.     must choose some behavior and document it.  Unspecified means
  1644.     that an implementation should choose some behavior, but need not
  1645.     document it.  Undefined means that absolutely anything might
  1646.     happen.  In no case does the Standard impose requirements; in
  1647.     the first two cases it occasionally suggests (and may require a
  1648.     choice from among) a small set of likely behaviors.
  1649.  
  1650.     If you're interested in writing portable code, you can ignore
  1651.     the distinctions, as you'll want to avoid code that depends on
  1652.     any of the three behaviors.
  1653.  
  1654.     References: ANSI Sec. 1.6, especially the Rationale.
  1655.  
  1656.  
  1657. Section 6. C Preprocessor
  1658.  
  1659. 6.1:    How can I write a generic macro to swap two values?
  1660.  
  1661. A:    There is no good answer to this question.  If the values are
  1662.     integers, a well-known trick using exclusive-OR could perhaps be
  1663.     used, but it will not work for floating-point values or
  1664.     pointers, or if the two values are the same variable (and the
  1665.     "obvious" supercompressed implementation for integral types
  1666.     a^=b^=a^=b is in fact illegal due to multiple side-effects; see
  1667.     questions 4.1 and 4.2).  If the macro is intended to be used on
  1668.     values of arbitrary type (the usual goal), it cannot use a
  1669.     temporary, since it does not know what type of temporary it
  1670.     needs, and standard C does not provide a typeof operator.
  1671.  
  1672.     The best all-around solution is probably to forget about using a
  1673.     macro, unless you're willing to pass in the type as a third
  1674.     argument.
  1675.  
  1676. 6.2:    I have some old code that tries to construct identifiers with a
  1677.     macro like
  1678.  
  1679.         #define Paste(a, b) a/**/b
  1680.  
  1681.     but it doesn't work any more.
  1682.  
  1683. A:    That comments disappeared entirely and could therefore be used
  1684.     for token pasting was an undocumented feature of some early
  1685.     preprocessor implementations, notably Reiser's.  ANSI affirms
  1686.     (as did K&R) that comments are replaced with white space.
  1687.     However, since the need for pasting tokens was demonstrated and
  1688.     real, ANSI introduced a well-defined token-pasting operator, ##,
  1689.     which can be used like this:
  1690.  
  1691.         #define Paste(a, b) a##b
  1692.  
  1693.     (See also question 5.4.)
  1694.  
  1695.     References: ANSI Sec. 3.8.3.3 p. 91, Rationale pp. 66-7.
  1696.  
  1697. 6.3:    What's the best way to write a multi-statement cpp macro?
  1698.  
  1699. A:    The usual goal is to write a macro that can be invoked as if it
  1700.     were a single function-call statement.  This means that the
  1701.     "caller" will be supplying the final semicolon, so the macro
  1702.     body should not.  The macro body cannot be a simple brace-
  1703.     delineated compound statement, because syntax errors would
  1704.     result if it were invoked (apparently as a single statement, but
  1705.     with a resultant extra semicolon) as the if branch of an if/else
  1706.     statement with an explicit else clause.
  1707.  
  1708.     The traditional solution is to use
  1709.  
  1710.         #define Func() do { \
  1711.             /* declarations */ \
  1712.             stmt1; \
  1713.             stmt2; \
  1714.             /* ... */ \
  1715.             } while(0)    /* (no trailing ; ) */
  1716.  
  1717.     When the "caller" appends a semicolon, this expansion becomes a
  1718.     single statement regardless of context.  (An optimizing compiler
  1719.     will remove any "dead" tests or branches on the constant
  1720.     condition 0, although lint may complain.)
  1721.  
  1722.     If all of the statements in the intended macro are simple
  1723.     expressions, with no declarations or loops, another technique is
  1724.     to write a single, parenthesized expression using one or more
  1725.     comma operators.  (See the example under question 6.10 below.
  1726.     This technique also allows a value to be "returned.")
  1727.  
  1728.     References: CT&P Sec. 6.3 pp. 82-3.
  1729.  
  1730. 6.4:    Is it acceptable for one header file to #include another?
  1731.  
  1732. A:    It's a question of style, and thus receives considerable debate.
  1733.     Many people believe that "nested #include files" are to be
  1734.     avoided: the prestigious Indian Hill Style Guide (see question
  1735.     14.3) disparages them; they can make it harder to find relevant
  1736.     definitions; they can lead to multiple-declaration errors if a
  1737.     file is #included twice; and they make manual Makefile
  1738.     maintenance very difficult.  On the other hand, they make it
  1739.     possible to use header files in a modular way (a header file
  1740.     #includes what it needs itself, rather than requiring each
  1741.     #includer to do so, a requirement that can lead to intractable
  1742.     headaches); a tool like grep (or a tags file) makes it easy to
  1743.     find definitions no matter where they are; a popular trick:
  1744.  
  1745.         #ifndef HEADERUSED
  1746.         #define HEADERUSED
  1747.         ...header file contents...
  1748.         #endif
  1749.  
  1750.     makes a header file "idempotent" so that it can safely be
  1751.     #included multiple times; and automated Makefile maintenance
  1752.     tools (which are a virtual necessity in large projects anyway)
  1753.     handle dependency generation in the face of nested #include
  1754.     files easily.  See also section 14.
  1755.  
  1756. 6.5:    Does the sizeof operator work in preprocessor #if directives?
  1757.  
  1758. A:    No.  Preprocessing happens during an earlier pass of
  1759.     compilation, before type names have been parsed.  Consider using
  1760.     the predefined constants in ANSI's <limits.h>, if applicable, or
  1761.     a "configure" script, instead.  (Better yet, try to write code
  1762.     which is inherently insensitive to type sizes.)
  1763.  
  1764.     References: ANSI Sec. 2.1.1.2 pp. 6-7, Sec. 3.8.1 p. 87
  1765.     footnote 83.
  1766.  
  1767. 6.6:    How can I use a preprocessor #if expression to tell if a machine
  1768.     is big-endian or little-endian?
  1769.  
  1770. A:    You probably can't.  (Preprocessor arithmetic uses only long
  1771.     ints, and there is no concept of addressing.)  Are you sure you
  1772.     need to know the machine's endianness explicitly?  Usually it's
  1773.     better to write code which doesn't care.
  1774.  
  1775. 6.7:    I've got this tricky processing I want to do at compile time and
  1776.     I can't figure out a way to get cpp to do it.
  1777.  
  1778. A:    cpp is not intended as a general-purpose preprocessor.  Rather
  1779.     than forcing it to do something inappropriate, consider writing
  1780.     your own little special-purpose preprocessing tool, instead.
  1781.     You can easily get a utility like make(1) to run it for you
  1782.     automatically.
  1783.  
  1784.     If you are trying to preprocess something other than C, consider
  1785.     using a general-purpose preprocessor (such as m4).
  1786.  
  1787. 6.8:    I inherited some code which contains far too many #ifdef's for
  1788.     my taste.  How can I preprocess the code to leave only one
  1789.     conditional compilation set, without running it through cpp and
  1790.     expanding all of the #include's and #define's as well?
  1791.  
  1792. A:    There are programs floating around called unifdef, rmifdef, and
  1793.     scpp which do exactly this.  (See question 17.12.)
  1794.  
  1795. 6.9:    How can I list all of the pre#defined identifiers?
  1796.  
  1797. A:    There's no standard way, although it is a frequent need.  If the
  1798.     compiler documentation is unhelpful, the most expedient way is
  1799.     probably to extract printable strings from the compiler or
  1800.     preprocessor executable with something like the Unix strings(1)
  1801.     utility.  Beware that many traditional system-selective
  1802.     pre#defined identifiers (e.g. "unix") are non-Standard (because
  1803.     they clash with the user's namespace) and are being removed or
  1804.     renamed.
  1805.  
  1806. 6.10:    How can I write a cpp macro which takes a variable number of
  1807.     arguments?
  1808.  
  1809. A:    One popular trick is to define the macro with a single argument,
  1810.     and call it with a double set of parentheses, which appear to
  1811.     the preprocessor to indicate a single argument:
  1812.  
  1813.         #define DEBUG(args) (printf("DEBUG: "), printf args)
  1814.  
  1815.         if(n != 0) DEBUG(("n is %d\n", n));
  1816.  
  1817.     The obvious disadvantage is that the caller must always remember
  1818.     to use the extra parentheses.  Other solutions are to use
  1819.     different macros (DEBUG1, DEBUG2, etc.) depending on the number
  1820.     of arguments, or to play games with commas:
  1821.  
  1822.         #define DEBUG(args) (printf("DEBUG: "), printf(args))
  1823.         #define _ ,
  1824.         DEBUG("i = %d" _ i)
  1825.  
  1826.     It is often better to use a bona-fide function, which can take a
  1827.     variable number of arguments in a well-defined way.  See
  1828.     questions 7.1 and 7.2.
  1829.  
  1830.  
  1831. Section 7. Variable-Length Argument Lists
  1832.  
  1833. 7.1:    How can I write a function that takes a variable number of
  1834.     arguments?
  1835.  
  1836. A:    Use the <stdarg.h> header (or, if you must, the older
  1837.     <varargs.h>).
  1838.  
  1839.     Here is a function which concatenates an arbitrary number of
  1840.     strings into malloc'ed memory:
  1841.  
  1842.         #include <stdlib.h>        /* for malloc, NULL, size_t */
  1843.         #include <stdarg.h>        /* for va_ stuff */
  1844.         #include <string.h>        /* for strcat et al */
  1845.  
  1846.         char *vstrcat(char *first, ...)
  1847.         {
  1848.             size_t len = 0;
  1849.             char *retbuf;
  1850.             va_list argp;
  1851.             char *p;
  1852.  
  1853.             if(first == NULL)
  1854.                 return NULL;
  1855.  
  1856.             len = strlen(first);
  1857.  
  1858.             va_start(argp, first);
  1859.  
  1860.             while((p = va_arg(argp, char *)) != NULL)
  1861.                 len += strlen(p);
  1862.  
  1863.             va_end(argp);
  1864.  
  1865.             retbuf = malloc(len + 1);    /* +1 for trailing \0 */
  1866.  
  1867.             if(retbuf == NULL)
  1868.                 return NULL;        /* error */
  1869.  
  1870.             (void)strcpy(retbuf, first);
  1871.  
  1872.             va_start(argp, first);
  1873.  
  1874.             while((p = va_arg(argp, char *)) != NULL)
  1875.                 (void)strcat(retbuf, p);
  1876.  
  1877.             va_end(argp);
  1878.  
  1879.             return retbuf;
  1880.         }
  1881.  
  1882.     Usage is something like
  1883.  
  1884.         char *str = vstrcat("Hello, ", "world!", (char *)NULL);
  1885.  
  1886.     Note the cast on the last argument.  (Also note that the caller
  1887.     must free the returned, malloc'ed storage.)
  1888.  
  1889.     Under a pre-ANSI compiler, rewrite the function definition
  1890.     without a prototype ("char *vstrcat(first) char *first; {"),
  1891.     include <stdio.h> rather than <stdlib.h>, add "extern
  1892.     char *malloc();", and use int instead of size_t.  You may also
  1893.     have to delete the (void) casts, and use the older varargs
  1894.     package instead of stdarg.  See the next question for hints.
  1895.  
  1896.     Remember that in variable-length argument lists, function
  1897.     prototypes do not supply parameter type information; therefore,
  1898.     default argument promotions apply (see question 5.8), and null
  1899.     pointer arguments must be typed explicitly (see question 1.2).
  1900.  
  1901.     References: K&R II Sec. 7.3 p. 155, Sec. B7 p. 254; H&S
  1902.     Sec. 13.4 pp. 286-9; ANSI Secs. 4.8 through 4.8.1.3 .
  1903.  
  1904. 7.2:    How can I write a function that takes a format string and a
  1905.     variable number of arguments, like printf, and passes them to
  1906.     printf to do most of the work?
  1907.  
  1908. A:    Use vprintf, vfprintf, or vsprintf.
  1909.  
  1910.     Here is an "error" routine which prints an error message,
  1911.     preceded by the string "error: " and terminated with a newline:
  1912.  
  1913.         #include <stdio.h>
  1914.         #include <stdarg.h>
  1915.  
  1916.         void
  1917.         error(char *fmt, ...)
  1918.         {
  1919.             va_list argp;
  1920.             fprintf(stderr, "error: ");
  1921.             va_start(argp, fmt);
  1922.             vfprintf(stderr, fmt, argp);
  1923.             va_end(argp);
  1924.             fprintf(stderr, "\n");
  1925.         }
  1926.  
  1927.     To use the older <varargs.h> package, instead of <stdarg.h>,
  1928.     change the function header to:
  1929.  
  1930.         void error(va_alist)
  1931.         va_dcl
  1932.         {
  1933.             char *fmt;
  1934.  
  1935.     change the va_start line to
  1936.  
  1937.         va_start(argp);
  1938.  
  1939.     and add the line
  1940.  
  1941.         fmt = va_arg(argp, char *);
  1942.  
  1943.     between the calls to va_start and vfprintf.  (Note that there is
  1944.     no semicolon after va_dcl.)
  1945.  
  1946.     References: K&R II Sec. 8.3 p. 174, Sec. B1.2 p. 245; H&S
  1947.     Sec. 17.12 p. 337; ANSI Secs. 4.9.6.7, 4.9.6.8, 4.9.6.9 .
  1948.  
  1949. 7.3:    How can I discover how many arguments a function was actually
  1950.     called with?
  1951.  
  1952. A:    This information is not available to a portable program.  Some
  1953.     old systems provided a nonstandard nargs() function, but its use
  1954.     was always questionable, since it typically returned the number
  1955.     of words passed, not the number of arguments.  (Structures and
  1956.     floating point values are usually passed as several words.)
  1957.  
  1958.     Any function which takes a variable number of arguments must be
  1959.     able to determine from the arguments themselves how many of them
  1960.     there are.  printf-like functions do this by looking for
  1961.     formatting specifiers (%d and the like) in the format string
  1962.     (which is why these functions fail badly if the format string
  1963.     does not match the argument list).  Another common technique
  1964.     (useful when the arguments are all of the same type) is to use a
  1965.     sentinel value (often 0, -1, or an appropriately-cast null
  1966.     pointer) at the end of the list (see the execl and vstrcat
  1967.     examples under questions 1.2 and 7.1 above).
  1968.  
  1969. 7.4:    I can't get the va_arg macro to pull in an argument of type
  1970.     pointer-to-function.
  1971.  
  1972. A:    The type-rewriting games which the va_arg macro typically plays
  1973.     are stymied by overly-complicated types such as pointer-to-
  1974.     function.  If you use a typedef for the function pointer type,
  1975.     however, all will be well.
  1976.  
  1977.     References: ANSI Sec. 4.8.1.2 p. 124.
  1978.  
  1979. 7.5:    How can I write a function which takes a variable number of
  1980.     arguments and passes them to some other function (which takes a
  1981.     variable number of arguments)?
  1982.  
  1983. A:    In general, you cannot.  You must provide a version of that
  1984.     other function which accepts a va_list pointer, as does vfprintf
  1985.     in the example above.  If the arguments must be passed directly
  1986.     as actual arguments (not indirectly through a va_list pointer)
  1987.     to another function which is itself variadic (for which you do
  1988.     not have the option of creating an alternate, va_list-accepting
  1989.     version) no portable solution is possible.  (The problem can be
  1990.     solved by resorting to machine-specific assembly language.)
  1991.  
  1992. 7.6:    How can I call a function with an argument list built up at run
  1993.     time?
  1994.  
  1995. A:    There is no guaranteed or portable way to do this.  If you're
  1996.     curious, ask this list's editor, who has a few wacky ideas you
  1997.     could try...  (See also question 16.11.)
  1998.  
  1999.  
  2000. Section 8. Boolean Expressions and Variables
  2001.  
  2002. 8.1:    What is the right type to use for boolean values in C?  Why
  2003.     isn't it a standard type?  Should #defines or enums be used for
  2004.     the true and false values?
  2005.  
  2006. A:    C does not provide a standard boolean type, because picking one
  2007.     involves a space/time tradeoff which is best decided by the
  2008.     programmer.  (Using an int for a boolean may be faster, while
  2009.     using char may save data space.)
  2010.  
  2011.     The choice between #defines and enums is arbitrary and not
  2012.     terribly interesting (see also question 9.1).  Use any of
  2013.  
  2014.         #define TRUE  1            #define YES 1
  2015.         #define FALSE 0            #define NO  0
  2016.  
  2017.         enum bool {false, true};    enum bool {no, yes};
  2018.  
  2019.     or use raw 1 and 0, as long as you are consistent within one
  2020.     program or project.  (An enum may be preferable if your debugger
  2021.     expands enum values when examining variables.)
  2022.  
  2023.     Some people prefer variants like
  2024.  
  2025.         #define TRUE (1==1)
  2026.         #define FALSE (!TRUE)
  2027.  
  2028.     or define "helper" macros such as
  2029.  
  2030.         #define Istrue(e) ((e) != 0)
  2031.  
  2032.     These don't buy anything (see question 8.2 below; see also
  2033.     question 1.6).
  2034.  
  2035. 8.2:    Isn't #defining TRUE to be 1 dangerous, since any nonzero value
  2036.     is considered "true" in C?  What if a built-in boolean or
  2037.     relational operator "returns" something other than 1?
  2038.  
  2039. A:    It is true (sic) that any nonzero value is considered true in C,
  2040.     but this applies only "on input", i.e. where a boolean value is
  2041.     expected.  When a boolean value is generated by a built-in
  2042.     operator, it is guaranteed to be 1 or 0.  Therefore, the test
  2043.  
  2044.         if((a == b) == TRUE)
  2045.  
  2046.     will work as expected (as long as TRUE is 1), but it is
  2047.     obviously silly.  In general, explicit tests against TRUE and
  2048.     FALSE are undesirable, because some library functions (notably
  2049.     isupper, isalpha, etc.) return, on success, a nonzero value
  2050.     which is _not_ necessarily 1.  (Besides, if you believe that
  2051.     "if((a == b) == TRUE)" is an improvement over "if(a == b)", why
  2052.     stop there?  Why not use "if(((a == b) == TRUE) == TRUE)"?)  A
  2053.     good rule of thumb is to use TRUE and FALSE (or the like) only
  2054.     for assignment to a Boolean variable or function parameter, or
  2055.     as the return value from a Boolean function, but never in a
  2056.     comparison.
  2057.  
  2058.     The preprocessor macros TRUE and FALSE are used for code
  2059.     readability, not because the underlying values might ever
  2060.     change.  (See also questions 1.7 and 1.9.)
  2061.  
  2062.     References: K&R I Sec. 2.7 p. 41; K&R II Sec. 2.6 p. 42,
  2063.     Sec. A7.4.7 p. 204, Sec. A7.9 p. 206; ANSI Secs. 3.3.3.3, 3.3.8,
  2064.     3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, 3.6.5; Achilles and the
  2065.     Tortoise.
  2066.  
  2067.  
  2068. Section 9. Structs, Enums, and Unions
  2069.  
  2070. 9.1:    What is the difference between an enum and a series of
  2071.     preprocessor #defines?
  2072.  
  2073. A:    At the present time, there is little difference.  Although many
  2074.     people might have wished otherwise, the ANSI standard says that
  2075.     enumerations may be freely intermixed with integral types,
  2076.     without errors.  (If such intermixing were disallowed without
  2077.     explicit casts, judicious use of enums could catch certain
  2078.     programming errors.)
  2079.  
  2080.     Some advantages of enums are that the numeric values are
  2081.     automatically assigned, that a debugger may be able to display
  2082.     the symbolic values when enum variables are examined, and that
  2083.     they obey block scope.  (A compiler may also generate nonfatal
  2084.     warnings when enums and ints are indiscriminately mixed, since
  2085.     doing so can still be considered bad style even though it is not
  2086.     strictly illegal).  A disadvantage is that the programmer has
  2087.     little control over the size (or over those nonfatal warnings).
  2088.  
  2089.     References: K&R II Sec. 2.3 p. 39, Sec. A4.2 p. 196; H&S
  2090.     Sec. 5.5 p. 100; ANSI Secs. 3.1.2.5, 3.5.2, 3.5.2.2 .
  2091.  
  2092. 9.2:    I heard that structures could be assigned to variables and
  2093.     passed to and from functions, but K&R I says not.
  2094.  
  2095. A:    What K&R I said was that the restrictions on struct operations
  2096.     would be lifted in a forthcoming version of the compiler, and in
  2097.     fact struct assignment and passing were fully functional in
  2098.     Ritchie's compiler even as K&R I was being published.  Although
  2099.     a few early C compilers lacked struct assignment, all modern
  2100.     compilers support it, and it is part of the ANSI C standard, so
  2101.     there should be no reluctance to use it.
  2102.  
  2103.     References: K&R I Sec. 6.2 p. 121; K&R II Sec. 6.2 p. 129; H&S
  2104.     Sec. 5.6.2 p. 103; ANSI Secs. 3.1.2.5, 3.2.2.1, 3.3.16 .
  2105.  
  2106. 9.3:    How does struct passing and returning work?
  2107.  
  2108. A:    When structures are passed as arguments to functions, the entire
  2109.     struct is typically pushed on the stack, using as many words as
  2110.     are required.  (Programmers often choose to use pointers to
  2111.     structures instead, precisely to avoid this overhead.)
  2112.  
  2113.     Structures are often returned from functions in a location
  2114.     pointed to by an extra, compiler-supplied "hidden" argument to
  2115.     the function.  Some older compilers used a special, static
  2116.     location for structure returns, although this made struct-valued
  2117.     functions nonreentrant, which ANSI C disallows.
  2118.  
  2119.     References: ANSI Sec. 2.2.3 p. 13.
  2120.  
  2121. 9.4:    The following program works correctly, but it dumps core after
  2122.     it finishes.  Why?
  2123.  
  2124.         struct list
  2125.             {
  2126.             char *item;
  2127.             struct list *next;
  2128.             }
  2129.  
  2130.         /* Here is the main program. */
  2131.  
  2132.         main(argc, argv)
  2133.         ...
  2134.  
  2135. A:    A missing semicolon causes the compiler to believe that main
  2136.     returns a structure.  (The connection is hard to see because of
  2137.     the intervening comment.)  Since struct-valued functions are
  2138.     usually implemented by adding a hidden return pointer, the
  2139.     generated code for main() tries to accept three arguments,
  2140.     although only two are passed (in this case, by the C start-up
  2141.     code).  See also question 17.21.
  2142.  
  2143.     References: CT&P Sec. 2.3 pp. 21-2.
  2144.  
  2145. 9.5:    Why can't you compare structs?
  2146.  
  2147. A:    There is no reasonable way for a compiler to implement struct
  2148.     comparison which is consistent with C's low-level flavor.  A
  2149.     byte-by-byte comparison could be invalidated by random bits
  2150.     present in unused "holes" in the structure (such padding is used
  2151.     to keep the alignment of later fields correct; see questions
  2152.     9.10 and 9.11).  A field-by-field comparison would require
  2153.     unacceptable amounts of repetitive, in-line code for large
  2154.     structures.
  2155.  
  2156.     If you want to compare two structures, you must write your own
  2157.     function to do so.  C++ would let you arrange for the ==
  2158.     operator to map to your function.
  2159.  
  2160.     References: K&R II Sec. 6.2 p. 129; H&S Sec. 5.6.2 p. 103; ANSI
  2161.     Rationale Sec. 3.3.9 p. 47.
  2162.  
  2163. 9.6:    How can I read/write structs from/to data files?
  2164.  
  2165. A:    It is relatively straightforward to write a struct out using
  2166.     fwrite:
  2167.  
  2168.         fwrite((char *)&somestruct, sizeof(somestruct), 1, fp);
  2169.  
  2170.     and a corresponding fread invocation can read it back in.
  2171.     However, data files so written will _not_ be very portable (see
  2172.     questions 9.11 and 17.3).  Note also that on many systems you
  2173.     must use the "b" flag when fopening the files.
  2174.  
  2175. 9.7:    I came across some code that declared a structure like this:
  2176.  
  2177.         struct name
  2178.             {
  2179.             int namelen;
  2180.             char name[1];
  2181.             };
  2182.  
  2183.     and then did some tricky allocation to make the name array act
  2184.     like it had several elements.  Is this legal and/or portable?
  2185.  
  2186. A:    This technique is popular, although Dennis Ritchie has called it
  2187.     "unwarranted chumminess with the C implementation."  An ANSI
  2188.     Interpretation Ruling has deemed it (more precisely, access
  2189.     beyond the declared size of the name field) to be not strictly
  2190.     conforming, although a thorough treatment of the arguments
  2191.     surrounding the legality of the technique is beyond the scope of
  2192.     this list.  It seems, however, to be portable to all known
  2193.     implementations.  (Compilers which check array bounds carefully
  2194.     might issue warnings.)
  2195.  
  2196.     To be on the safe side, it may be preferable to declare the
  2197.     variable-size element very large, rather than very small; in the
  2198.     case of the above example:
  2199.  
  2200.         ...
  2201.         char name[MAXSIZE];
  2202.         ...
  2203.  
  2204.     where MAXSIZE is larger than any name which will be stored.
  2205.     (The trick so modified is said to be in conformance with the
  2206.     Standard.)
  2207.  
  2208.     References: ANSI Rationale Sec. 3.5.4.2 pp. 54-5.
  2209.  
  2210. 9.8:    How can I determine the byte offset of a field within a
  2211.     structure?
  2212.  
  2213. A:    ANSI C defines the offsetof macro, which should be used if
  2214.     available; see <stddef.h>.  If you don't have it, a suggested
  2215.     implementation is
  2216.  
  2217.         #define offsetof(type, mem) ((size_t) \
  2218.             ((char *)&((type *) 0)->mem - (char *)((type *) 0)))
  2219.  
  2220.     This implementation is not 100% portable; some compilers may
  2221.     legitimately refuse to accept it.
  2222.  
  2223.     See the next question for a usage hint.
  2224.  
  2225.     References: ANSI Sec. 4.1.5, Rationale Sec. 3.5.4.2 p. 55.
  2226.  
  2227. 9.9:    How can I access structure fields by name at run time?
  2228.  
  2229. A:    Build a table of names and offsets, using the offsetof() macro.
  2230.     The offset of field b in struct a is
  2231.  
  2232.         offsetb = offsetof(struct a, b)
  2233.  
  2234.     If structp is a pointer to an instance of this structure, and b
  2235.     is an int field with offset as computed above, b's value can be
  2236.     set indirectly with
  2237.  
  2238.         *(int *)((char *)structp + offsetb) = value;
  2239.  
  2240. 9.10:    Why does sizeof report a larger size than I expect for a
  2241.     structure type, as if there was padding at the end?
  2242.  
  2243. A:    Structures may have this padding (as well as internal padding;
  2244.     see also question 9.5), so that alignment properties will be
  2245.     preserved when an array of contiguous structures is allocated.
  2246.  
  2247. 9.11:    My compiler is leaving holes in structures, which is wasting
  2248.     space and preventing "binary" I/O to external data files.  Can I
  2249.     turn off the padding, or otherwise control the alignment of
  2250.     structs?
  2251.  
  2252. A:    Your compiler may provide an extension to give you this control
  2253.     (perhaps a #pragma), but there is no standard method.  See also
  2254.     question 17.3.
  2255.  
  2256. 9.12:    Can I initialize unions?
  2257.  
  2258. A:    ANSI Standard C allows an initializer for the first member of a
  2259.     union.  There is no standard way of initializing the other
  2260.     members (nor, under a pre-ANSI compiler, is there generally any
  2261.     way of initializing any of them).
  2262.  
  2263. 9.13:    How can I pass constant values to routines which accept struct
  2264.     arguments?
  2265.  
  2266. A:    C has no way of generating anonymous struct values.  You will
  2267.     have to use a temporary struct variable.
  2268.  
  2269.  
  2270. Section 10. Declarations
  2271.  
  2272. 10.1:    How do you decide which integer type to use?
  2273.  
  2274. A:    If you might need large values (above 32767 or below -32767),
  2275.     use long.  Otherwise, if space is very important (there are
  2276.     large arrays or many structures), use short.  Otherwise, use
  2277.     int.  If well-defined overflow characteristics are important
  2278.     and/or negative values are not, use the corresponding unsigned
  2279.     types.  (But beware of mixing signed and unsigned in
  2280.     expressions.)  Similar arguments apply when deciding between
  2281.     float and double.
  2282.  
  2283.     Although char or unsigned char can be used as a "tiny" int type,
  2284.     doing so is often more trouble than it's worth, due to
  2285.     unpredictable sign extension and increased code size.
  2286.  
  2287.     These rules obviously don't apply if the address of a variable
  2288.     is taken and must have a particular type.
  2289.  
  2290.     If for some reason you need to declare something with an _exact_
  2291.     size (usually the only good reason for doing so is when
  2292.     attempting to conform to some externally-imposed storage layout,
  2293.     but see question 17.3), be sure to encapsulate the choice behind
  2294.     an appropriate typedef.
  2295.  
  2296. 10.2:    What should the 64-bit type on new, 64-bit machines be?
  2297.  
  2298. A:    Some vendors of C products for 64-bit machines support 64-bit
  2299.     long ints.  Others fear that too much existing code depends on
  2300.     sizeof(int) == sizeof(long) == 32 bits, and introduce a new 64-
  2301.     bit long long (or __longlong) type instead.
  2302.  
  2303.     Programmers interested in writing portable code should therefore
  2304.     insulate their 64-bit type needs behind appropriate typedefs.
  2305.     Vendors who feel compelled to introduce a new, longer integral
  2306.     type should advertise it as being "at least 64 bits" (which is
  2307.     truly new; a type traditional C doesn't have), and not "exactly
  2308.     64 bits."
  2309.  
  2310. 10.3:    I can't seem to define a linked list successfully.  I tried
  2311.  
  2312.         typedef struct
  2313.             {
  2314.             char *item;
  2315.             NODEPTR next;
  2316.             } *NODEPTR;
  2317.  
  2318.     but the compiler gave me error messages.  Can't a struct in C
  2319.     contain a pointer to itself?
  2320.  
  2321. A:    Structs in C can certainly contain pointers to themselves; the
  2322.     discussion and example in section 6.5 of K&R make this clear.
  2323.     The problem with this example is that the NODEPTR typedef is not
  2324.     complete at the point where the "next" field is declared.  To
  2325.     fix it, first give the structure a tag ("struct node").  Then,
  2326.     declare the "next" field as "struct node *next;", and/or move
  2327.     the typedef declaration wholly before or wholly after the struct
  2328.     declaration.  One corrected version would be
  2329.  
  2330.         struct node
  2331.             {
  2332.             char *item;
  2333.             struct node *next;
  2334.             };
  2335.  
  2336.         typedef struct node *NODEPTR;
  2337.  
  2338.     , and there are at least three other equivalently correct ways
  2339.     of arranging it.
  2340.  
  2341.     A similar problem, with a similar solution, can arise when
  2342.     attempting to declare a pair of typedef'ed mutually referential
  2343.     structures.
  2344.  
  2345.     References: K&R I Sec. 6.5 p. 101; K&R II Sec. 6.5 p. 139; H&S
  2346.     Sec. 5.6.1 p. 102; ANSI Sec. 3.5.2.3 .
  2347.  
  2348. 10.4:    How do I declare an array of N pointers to functions returning
  2349.     pointers to functions returning pointers to characters?
  2350.  
  2351. A:    This question can be answered in at least three ways:
  2352.  
  2353.     1.  char *(*(*a[N])())();
  2354.  
  2355.     2.  Build the declaration up in stages, using typedefs:
  2356.  
  2357.         typedef char *pc;    /* pointer to char */
  2358.         typedef pc fpc();    /* function returning pointer to char */
  2359.         typedef fpc *pfpc;    /* pointer to above */
  2360.         typedef pfpc fpfpc();    /* function returning... */
  2361.         typedef fpfpc *pfpfpc;    /* pointer to... */
  2362.         pfpfpc a[N];        /* array of... */
  2363.  
  2364.     3.  Use the cdecl program, which turns English into C and vice
  2365.         versa:
  2366.  
  2367.         cdecl> declare a as array of pointer to function returning
  2368.              pointer to function returning pointer to char
  2369.         char *(*(*a[])())()
  2370.  
  2371.         cdecl can also explain complicated declarations, help with
  2372.         casts, and indicate which set of parentheses the arguments
  2373.         go in (for complicated function definitions, like the
  2374.         above).  Versions of cdecl are in volume 14 of
  2375.         comp.sources.unix (see question 17.12) and K&R II.
  2376.  
  2377.     Any good book on C should explain how to read these complicated
  2378.     C declarations "inside out" to understand them ("declaration
  2379.     mimics use").
  2380.  
  2381.     References: K&R II Sec. 5.12 p. 122; H&S Sec. 5.10.1 p. 116.
  2382.  
  2383. 10.5:    I'm building a state machine with a bunch of functions, one for
  2384.     each state.  I want to implement state transitions by having
  2385.     each function return a pointer to the next state function.  I
  2386.     find a limitation in C's declaration mechanism: there's no way
  2387.     to declare these functions as returning a pointer to a function
  2388.     returning a pointer to a function returning a pointer to a
  2389.     function...
  2390.  
  2391. A:    You can't do it directly.  Either have the function return a
  2392.     generic function pointer type, and apply a cast before calling
  2393.     through it; or have it return a structure containing only a
  2394.     pointer to a function returning that structure.
  2395.  
  2396. 10.6:    My compiler is complaining about an invalid redeclaration of a
  2397.     function, but I only define it once and call it once.
  2398.  
  2399. A:    Functions which are called without a declaration in scope (or
  2400.     before they are declared) are assumed to be declared as
  2401.     returning int, leading to discrepancies if the function is later
  2402.     declared otherwise.  Non-int functions must be declared before
  2403.     they are called.
  2404.  
  2405.     References: K&R I Sec. 4.2 pp. 70; K&R II Sec. 4.2 p. 72; ANSI
  2406.     Sec. 3.3.2.2 .
  2407.  
  2408. 10.7:    What's the best way to declare and define global variables?
  2409.  
  2410. A:    First, though there can be many _declarations_ (and in many
  2411.     translation units) of a single "global" (strictly speaking,
  2412.     "external") variable (or function), there must be exactly one
  2413.     _definition_.  (The definition is the declaration that actually
  2414.     allocates space, and provides an initialization value, if any.)
  2415.     It is best to place the definition in some central (to the
  2416.     program, or to the module) .c file, with an external declaration
  2417.     in a header (".h") file, which is #included wherever the
  2418.     declaration is needed.  The .c file containing the definition
  2419.     should also #include the header file containing the external
  2420.     declaration, so that the compiler can check that the
  2421.     declarations match.
  2422.  
  2423.     This rule promotes a high degree of portability, and is
  2424.     consistent with the requirements of the ANSI C Standard.  Note
  2425.     that Unix compilers and linkers typically use a "common model"
  2426.     which allows multiple (uninitialized) definitions.  A few very
  2427.     odd systems may require an explicit initializer to distinguish a
  2428.     definition from an external declaration.
  2429.  
  2430.     It is possible to use preprocessor tricks to arrange that the
  2431.     declaration need only be typed once, in the header file, and
  2432.     "turned into" a definition, during exactly one #inclusion, via a
  2433.     special #define.
  2434.  
  2435.     References: K&R I Sec. 4.5 pp. 76-7; K&R II Sec. 4.4 pp. 80-1;
  2436.     ANSI Sec. 3.1.2.2 (esp. Rationale), Secs. 3.7, 3.7.2,
  2437.     Sec. F.5.11; H&S Sec. 4.8 pp. 79-80; CT&P Sec. 4.2 pp. 54-56.
  2438.  
  2439. 10.8:    What does extern mean in a function declaration?
  2440.  
  2441. A:    It can be used as a stylistic hint to indicate that the
  2442.     function's definition is probably in another source file, but
  2443.     there is no formal difference between
  2444.  
  2445.         extern int f();
  2446.     and
  2447.         int f();
  2448.  
  2449.     References: ANSI Sec. 3.1.2.2 .
  2450.  
  2451. 10.9:    I finally figured out the syntax for declaring pointers to
  2452.     functions, but now how do I initialize one?
  2453.  
  2454. A:    Use something like
  2455.  
  2456.         extern int func();
  2457.         int (*fp)() = func;
  2458.  
  2459.     When the name of a function appears in an expression but is not
  2460.     being called (i.e. is not followed by a "("), it "decays" into a
  2461.     pointer (i.e. it has its address implicitly taken), much as an
  2462.     array name does.
  2463.  
  2464.     An explicit extern declaration for the function is normally
  2465.     needed, since implicit external function declaration does not
  2466.     happen in this case (again, because the function name is not
  2467.     followed by a "(").
  2468.  
  2469. 10.10:    I've seen different methods used for calling through pointers to
  2470.     functions.  What's the story?
  2471.  
  2472. A:    Originally, a pointer to a function had to be "turned into" a
  2473.     "real" function, with the * operator (and an extra pair of
  2474.     parentheses, to keep the precedence straight), before calling:
  2475.  
  2476.         int r, func(), (*fp)() = func;
  2477.         r = (*fp)();
  2478.  
  2479.     It can also be argued that functions are always called through
  2480.     pointers, but that "real" functions decay implicitly into
  2481.     pointers (in expressions, as they do in initializations) and so
  2482.     cause no trouble.  This reasoning, made widespread through pcc
  2483.     and adopted in the ANSI standard, means that
  2484.  
  2485.         r = fp();
  2486.  
  2487.     is legal and works correctly, whether fp is a function or a
  2488.     pointer to one.  (The usage has always been unambiguous; there
  2489.     is nothing you ever could have done with a function pointer
  2490.     followed by an argument list except call through it.)  An
  2491.     explicit * is harmless, and still allowed (and recommended, if
  2492.     portability to older compilers is important).
  2493.  
  2494.     References: ANSI Sec. 3.3.2.2 p. 41, Rationale p. 41.
  2495.  
  2496. 10.11:    What's the auto keyword good for?
  2497.  
  2498. A:    Nothing; it's obsolete.
  2499.  
  2500.  
  2501. Section 11. Stdio
  2502.  
  2503. 11.1:    What's wrong with this code:
  2504.  
  2505.         char c;
  2506.         while((c = getchar()) != EOF)...
  2507.  
  2508. A:    For one thing, the variable to hold getchar's return value must
  2509.     be an int.  getchar can return all possible character values, as
  2510.     well as EOF.  By passing getchar's return value through a char,
  2511.     either a normal character might be misinterpreted as EOF, or the
  2512.     EOF might be altered (particularly if type char is unsigned) and
  2513.     so never seen.
  2514.  
  2515.     References: CT&P Sec. 5.1 p. 70.
  2516.  
  2517. 11.2:    How can I print a '%' character in a printf format string?  I
  2518.     tried \%, but it didn't work.
  2519.  
  2520. A:    Simply double the percent sign: %% .
  2521.  
  2522.     References: K&R I Sec. 7.3 p. 147; K&R II Sec. 7.2 p. 154; ANSI
  2523.     Sec. 4.9.6.1 .
  2524.  
  2525. 11.3:    Why doesn't the code scanf("%d", i); work?
  2526.  
  2527. A:    scanf needs pointers to the variables it is to fill in; you must
  2528.     call scanf("%d", &i);
  2529.  
  2530. 11.4:    Why doesn't this code:
  2531.  
  2532.         double d;
  2533.         scanf("%f", &d);
  2534.  
  2535.     work?
  2536.  
  2537. A:    scanf uses %lf for values of type double, and %f for float.
  2538.     (Note the discrepancy with printf, which uses %f for both double
  2539.     and float, due to C's default argument promotion rules.)
  2540.  
  2541. 11.5:    Why won't the code
  2542.  
  2543.         while(!feof(infp)) {
  2544.             fgets(buf, MAXLINE, infp);
  2545.             fputs(buf, outfp);
  2546.         }
  2547.  
  2548.     work?
  2549.  
  2550. A:    C's I/O is not like Pascal's.  EOF is only indicated _after_ an
  2551.     input routine has tried to read, and has reached end-of-file.
  2552.     Usually, you should just check the return value of the input
  2553.     routine (fgets in this case); often, you don't need to use
  2554.     feof() at all.
  2555.  
  2556. 11.6:    Why does everyone say not to use gets()?
  2557.  
  2558. A:    It cannot be told the size of the buffer it's to read into, so
  2559.     it cannot be prevented from overflowing that buffer.  See
  2560.     question 3.1 for a code fragment illustrating the replacement of
  2561.     gets() with fgets().
  2562.  
  2563. 11.7:    Why does errno contain ENOTTY after a call to printf?
  2564.  
  2565. A:    Many implementations of the stdio package adjust their behavior
  2566.     slightly if stdout is a terminal.  To make the determination,
  2567.     these implementations perform an operation which fails (with
  2568.     ENOTTY) if stdout is not a terminal.  Although the output
  2569.     operation goes on to complete successfully, errno still contains
  2570.     ENOTTY.
  2571.  
  2572.     References: CT&P Sec. 5.4 p. 73.
  2573.  
  2574. 11.8:    My program's prompts and intermediate output don't always show
  2575.     up on the screen, especially when I pipe the output through
  2576.     another program.
  2577.  
  2578. A:    It is best to use an explicit fflush(stdout) whenever output
  2579.     should definitely be visible.  Several mechanisms attempt to
  2580.     perform the fflush for you, at the "right time," but they tend
  2581.     to apply only when stdout is a terminal.  (See question 11.7.)
  2582.  
  2583. 11.9:    When I read from the keyboard with scanf, it seems to hang until
  2584.     I type one extra line of input.
  2585.  
  2586. A:    scanf was designed for free-format input, which is seldom what
  2587.     you want when reading from the keyboard.  In particular, "\n" in
  2588.     a format string does _not_ mean to expect a newline, but rather
  2589.     to read and discard characters as long as each is a whitespace
  2590.     character.
  2591.  
  2592.     A related problem is that unexpected non-numeric input can cause
  2593.     scanf to "jam."  Because of these problems, it is usually better
  2594.     to use fgets to read a whole line, and then use sscanf or other
  2595.     string functions to pick apart the line buffer.  If you do use
  2596.     sscanf, don't forget to check the return value to make sure that
  2597.     the expected number of items were found.
  2598.  
  2599. 11.10:    I'm trying to update a file in place, by using fopen mode "r+",
  2600.     then reading a certain string, and finally writing back a
  2601.     modified string, but it's not working.
  2602.  
  2603. A:    Be sure to call fseek before you write, both to seek back to the
  2604.     beginning of the string you're trying to overwrite, and because
  2605.     an fseek or fflush is always required between reading and
  2606.     writing in the read/write "+" modes.  Also, remember that you
  2607.     can only overwrite characters with the same number of
  2608.     replacement characters; see also question 17.4.
  2609.  
  2610.     References: ANSI Sec. 4.9.5.3 p. 131.
  2611.  
  2612. 11.11:    How can I read one character at a time, without waiting for the
  2613.     RETURN key?
  2614.  
  2615. A:    See question 16.1.
  2616.  
  2617. 11.12:    How can I flush pending input so that a user's typeahead isn't
  2618.     read at the next prompt?  Will fflush(stdin) work?
  2619.  
  2620. A:    fflush is defined only for output streams.  Since its definition
  2621.     of "flush" is to complete the writing of buffered characters
  2622.     (not to discard them), discarding unread input would not be an
  2623.     analogous meaning for fflush on input streams.  There is no
  2624.     standard way to discard unread characters from a stdio input
  2625.     buffer, nor would such a way be sufficient; unread characters
  2626.     can also accumulate in other, OS-level input buffers.
  2627.  
  2628. 11.13:    How can I redirect stdin or stdout to a file from within a
  2629.     program?
  2630.  
  2631. A:    Use freopen.
  2632.  
  2633. 11.14:    Once I've used freopen, how can I get the original stdout (or
  2634.     stdin) back?
  2635.  
  2636. A:    If you need to switch back and forth, the best all-around
  2637.     solution is not to use freopen in the first place.  Try using
  2638.     your own explicit output (or input) stream variable, which you
  2639.     can reassign at will, while leaving the original stdout (or
  2640.     stdin) undisturbed.
  2641.  
  2642. 11.15:    How can I recover the file name given an open file descriptor?
  2643.  
  2644. A:    This problem is, in general, insoluble.  Under Unix, for
  2645.     instance, a scan of the entire disk, (perhaps requiring special
  2646.     permissions) would theoretically be required, and would fail if
  2647.     the file descriptor was a pipe or referred to a deleted file
  2648.     (and could give a misleading answer for a file with multiple
  2649.     links).  It is best to remember the names of files yourself when
  2650.     you open them (perhaps with a wrapper function around fopen).
  2651.  
  2652.  
  2653. Section 12. Library Subroutines
  2654.  
  2655. 12.1:    Why does strncpy not always place a '\0' termination in the
  2656.     destination string?
  2657.  
  2658. A:    strncpy was first designed to handle a now-obsolete data
  2659.     structure, the fixed-length, not-necessarily-\0-terminated
  2660.     "string."  strncpy is admittedly a bit cumbersome to use in
  2661.     other contexts, since you must often append a '\0' to the
  2662.     destination string by hand.
  2663.  
  2664. 12.2:    I'm trying to sort an array of strings with qsort, using strcmp
  2665.     as the comparison function, but it's not working.
  2666.  
  2667. A:    By "array of strings" you probably mean "array of pointers to
  2668.     char."  The arguments to qsort's comparison function are
  2669.     pointers to the objects being sorted, in this case, pointers to
  2670.     pointers to char.  (strcmp, of course, accepts simple pointers
  2671.     to char.)
  2672.  
  2673.     The comparison routine's arguments are expressed as "generic
  2674.     pointers," const void * or char *.  They must be converted back
  2675.     to what they "really are" (char **) and dereferenced, yielding
  2676.     char *'s which can be usefully compared.  Write a comparison
  2677.     function like this:
  2678.  
  2679.         int pstrcmp(p1, p2)    /* compare strings through pointers */
  2680.         char *p1, *p2;        /* const void * for ANSI C */
  2681.         {
  2682.             return strcmp(*(char **)p1, *(char **)p2);
  2683.         }
  2684.  
  2685.     Beware of the discussion in K&R II Sec. 5.11 pp. 119-20, which
  2686.     is not discussing Standard library qsort.
  2687.  
  2688. 12.3:    Now I'm trying to sort an array of structures with qsort.  My
  2689.     comparison routine takes pointers to structures, but the
  2690.     compiler complains that the function is of the wrong type for
  2691.     qsort.  How can I cast the function pointer to shut off the
  2692.     warning?
  2693.  
  2694. A:    The conversions must be in the comparison function, which must
  2695.     be declared as accepting "generic pointers" (const void * or
  2696.     char *) as discussed in question 12.2 above.  The code might
  2697.     look like
  2698.  
  2699.         int mystructcmp(p1, p2)
  2700.         char *p1, *p2;        /* const void * for ANSI C */
  2701.         {
  2702.             struct mystruct *sp1 = (struct mystruct *)p1;
  2703.             struct mystruct *sp2 = (struct mystruct *)p2;
  2704.             /* now compare sp1->whatever and sp2-> ... */
  2705.         }
  2706.  
  2707.     (If, on the other hand, you're sorting pointers to structures,
  2708.     you'll need indirection, as in question 12.2:
  2709.     sp1 = *(struct mystruct **)p1 .)
  2710.  
  2711. 12.4:    How can I convert numbers to strings (the opposite of atoi)?  Is
  2712.     there an itoa function?
  2713.  
  2714. A:    Just use sprintf.  (You'll have to allocate space for the result
  2715.     somewhere anyway; see questions 3.1 and 3.2.  Don't worry that
  2716.     sprintf may be overkill, potentially wasting run time or code
  2717.     space; it works well in practice.)
  2718.  
  2719.     References: K&R I Sec. 3.6 p. 60; K&R II Sec. 3.6 p. 64.
  2720.  
  2721. 12.5:    How can I get the current date or time of day in a C program?
  2722.  
  2723. A:    Just use the time, ctime, and/or localtime functions.  (These
  2724.     routines have been around for years, and are in the ANSI
  2725.     standard.)  Here is a simple example:
  2726.  
  2727.         #include <stdio.h>
  2728.         #include <time.h>
  2729.  
  2730.         main()
  2731.         {
  2732.             time_t now = time((time_t *)NULL);
  2733.             printf("It's %.24s.\n", ctime(&now));
  2734.             return 0;
  2735.         }
  2736.  
  2737.     References: ANSI Sec. 4.12 .
  2738.  
  2739. 12.6:    I know that the library routine localtime will convert a time_t
  2740.     into a broken-down struct tm, and that ctime will convert a
  2741.     time_t to a printable string.  How can I perform the inverse
  2742.     operations of converting a struct tm or a string into a time_t?
  2743.  
  2744. A:    ANSI C specifies a library routine, mktime, which converts a
  2745.     struct tm to a time_t.  Several public-domain versions of this
  2746.     routine are available in case your compiler does not support it
  2747.     yet.
  2748.  
  2749.     Converting a string to a time_t is harder, because of the wide
  2750.     variety of date and time formats which should be parsed.  Some
  2751.     systems provide a strptime function; another popular routine is
  2752.     partime (widely distributed with the RCS package), but these are
  2753.     less likely to become standardized.
  2754.  
  2755.     References: K&R II Sec. B10 p. 256; H&S Sec. 20.4 p. 361; ANSI
  2756.     Sec. 4.12.2.3 .
  2757.  
  2758. 12.7:    How can I add n days to a date?  How can I find the difference
  2759.     between two dates?
  2760.  
  2761. A:    The ANSI/ISO Standard C mktime and difftime functions provide
  2762.     some support for both problems.  mktime() accepts non-normalized
  2763.     dates, so it is straightforward to take a filled-in struct tm,
  2764.     add or subtract from the tm_mday field, and call mktime() to
  2765.     normalize the year, month, and day fields (and convert to a
  2766.     time_t value).  difftime() computes the difference, in seconds,
  2767.     between two time_t values; mktime() can be used to compute
  2768.     time_t values for two dates to be subtracted.  (Note, however,
  2769.     that these solutions only work for dates in the range which can
  2770.     be represented as time_t's, and that not all days are 86400
  2771.     seconds long.)  See also questions 12.6 and 17.28.
  2772.  
  2773.     References: K&R II Sec. B10 p. 256; H&S Secs. 20.4, 20.5
  2774.     pp. 361-362; ANSI Secs. 4.12.2.2, 4.12.2.3 .
  2775.  
  2776. 12.8:    I need a random number generator.
  2777.  
  2778. A:    The standard C library has one: rand().  The implementation on
  2779.     your system may not be perfect, but writing a better one isn't
  2780.     necessarily easy, either.
  2781.  
  2782.     References: ANSI Sec. 4.10.2.1 p. 154; Knuth Vol. 2 Chap. 3
  2783.     pp. 1-177.
  2784.  
  2785. 12.9:    How can I get random integers in a certain range?
  2786.  
  2787. A:    The obvious way,
  2788.  
  2789.         rand() % N
  2790.  
  2791.     (where N is of course the range) is poor, because the low-order
  2792.     bits of many random number generators are distressingly non-
  2793.     random.  (See question 12.11.)  A better method is something
  2794.     like
  2795.  
  2796.         (int)((double)rand() / ((double)RAND_MAX + 1) * N)
  2797.  
  2798.     If you're worried about using floating point, you could try
  2799.  
  2800.         rand() / (RAND_MAX / N + 1)
  2801.  
  2802.     Both methods obviously require knowing RAND_MAX (which ANSI
  2803.     defines in <stdlib.h>), and assume that N is much less than
  2804.     RAND_MAX.
  2805.  
  2806. 12.10:    Each time I run my program, I get the same sequence of numbers
  2807.     back from rand().
  2808.  
  2809. A:    You can call srand() to seed the pseudo-random number generator
  2810.     with a more random initial value.  Popular seed values are the
  2811.     time of day, or the elapsed time before the user presses a key
  2812.     (although keypress times are hard to determine portably; see
  2813.     question 16.10).
  2814.  
  2815.     References: ANSI Sec. 4.10.2.2 p. 154.
  2816.  
  2817. 12.11:    I need a random true/false value, so I'm taking rand() % 2, but
  2818.     it's just alternating 0, 1, 0, 1, 0...
  2819.  
  2820. A:    Poor pseudorandom number generators (such as the ones
  2821.     unfortunately supplied with some systems) are not very random in
  2822.     the low-order bits.  Try using the higher-order bits.  See
  2823.     question 12.9.
  2824.  
  2825. 12.12:    I'm trying to port this        A:  Those routines are variously
  2826.     old program.  Why do I            obsolete; you should
  2827.     get "undefined external"        instead:
  2828.     errors for:
  2829.  
  2830.     index?                    use strchr.
  2831.     rindex?                    use strrchr.
  2832.     bcopy?                    use memmove, after
  2833.                         interchanging the first and
  2834.                         second arguments (see also
  2835.                         question 5.15).
  2836.     bcmp?                    use memcmp.
  2837.     bzero?                    use memset, with a second
  2838.                         argument of 0.
  2839.  
  2840. 12.13:    I keep getting errors due to library routines being undefined,
  2841.     but I'm #including all the right header files.
  2842.  
  2843. A:    In some cases (especially if the routines are nonstandard) you
  2844.     may have to explicitly ask for the correct libraries to be
  2845.     searched when you link the program.  See also question 15.2.
  2846.  
  2847. 12.14:    I'm still getting errors due to library routines being
  2848.     undefined, even though I'm using -l to request the libraries
  2849.     while linking.
  2850.  
  2851. A:    Many linkers make one pass over the list of object files and
  2852.     libraries you specify, and extract from libraries only those
  2853.     modules which satisfy references which have so far come up as
  2854.     undefined.  Therefore, the order in which libraries are listed
  2855.     with respect to object files (and each other) is significant;
  2856.     usually, you want to search the libraries last.  (For example,
  2857.     under Unix, put any -l switches towards the end of the command
  2858.     line.)
  2859.  
  2860. 12.15:    I need some code to do regular expression matching.
  2861.  
  2862. A:    Look for the regexp library (supplied with many Unix systems),
  2863.     or get Henry Spencer's regexp package from cs.toronto.edu in
  2864.     pub/regexp.shar.Z (see also question 17.12).
  2865.  
  2866. 12.16:    How can I split up a command line into whitespace-separated
  2867.     arguments, like main's argc and argv?
  2868.  
  2869. A:    Most systems have a routine called strtok, although it can be
  2870.     tricky to use and it may not do everything you want it to (e.g.,
  2871.     quoting).
  2872.  
  2873.     References: ANSI Sec. 4.11.5.8; K&R II Sec. B3 p. 250; H&S
  2874.     Sec. 15.7; PCS p. 178.
  2875.  
  2876.  
  2877. Section 13. Lint
  2878.  
  2879. 13.1:    I just typed in this program, and it's acting strangely.  Can
  2880.     you see anything wrong with it?
  2881.  
  2882. A:    Try running lint first (perhaps with the -a, -c, -h, -p and/or
  2883.     other options).  Many C compilers are really only half-
  2884.     compilers, electing not to diagnose numerous source code
  2885.     difficulties which would not actively preclude code generation.
  2886.  
  2887. 13.2:    How can I shut off the "warning: possible pointer alignment
  2888.     problem" message lint gives me for each call to malloc?
  2889.  
  2890. A:    The problem is that traditional versions of lint do not know,
  2891.     and cannot be told, that malloc "returns a pointer to space
  2892.     suitably aligned for storage of any type of object."  It is
  2893.     possible to provide a pseudoimplementation of malloc, using a
  2894.     #define inside of #ifdef lint, which effectively shuts this
  2895.     warning off, but a simpleminded #definition will also suppress
  2896.     meaningful messages about truly incorrect invocations.  It may
  2897.     be easier simply to ignore the message, perhaps in an automated
  2898.     way with grep -v.
  2899.  
  2900. 13.3:    Where can I get an ANSI-compatible lint?
  2901.  
  2902. A:    A product called FlexeLint is available (in "shrouded source
  2903.     form," for compilation on 'most any system) from
  2904.  
  2905.         Gimpel Software
  2906.         3207 Hogarth Lane
  2907.         Collegeville, PA  19426  USA
  2908.         (+1) 215 584 4261
  2909.  
  2910.     The System V release 4 lint is ANSI-compatible, and is available
  2911.     separately (bundled with other C tools) from UNIX Support Labs
  2912.     or from System V resellers.
  2913.  
  2914.     In the absence of lint, many modern compilers attempt to
  2915.     diagnose almost as many problems as a good lint does.
  2916.  
  2917. Section 14. Style
  2918.  
  2919. 14.1:    Here's a neat trick:
  2920.  
  2921.         if(!strcmp(s1, s2))
  2922.  
  2923.     Is this good style?
  2924.  
  2925. A:    It is not particularly good style, although it is a popular
  2926.     idiom.  The test succeeds if the two strings are equal, but its
  2927.     form suggests that it tests for inequality.
  2928.  
  2929.     Another solution is to use a macro:
  2930.  
  2931.         #define Streq(s1, s2) (strcmp((s1), (s2)) == 0)
  2932.  
  2933.     Opinions on code style, like those on religion, can be debated
  2934.     endlessly.  Though good style is a worthy goal, and can usually
  2935.     be recognized, it cannot be codified.
  2936.  
  2937. 14.2:    What's the best style for code layout in C?
  2938.  
  2939. A:    K&R, while providing the example most often copied, also supply
  2940.     a good excuse for avoiding it:
  2941.  
  2942.         The position of braces is less important,
  2943.         although people hold passionate beliefs.  We
  2944.         have chosen one of several popular styles.  Pick
  2945.         a style that suits you, then use it
  2946.         consistently.
  2947.  
  2948.     It is more important that the layout chosen be consistent (with
  2949.     itself, and with nearby or common code) than that it be
  2950.     "perfect."  If your coding environment (i.e. local custom or
  2951.     company policy) does not suggest a style, and you don't feel
  2952.     like inventing your own, just copy K&R.  (The tradeoffs between
  2953.     various indenting and brace placement options can be
  2954.     exhaustively and minutely examined, but don't warrant repetition
  2955.     here.  See also the Indian Hill Style Guide.)
  2956.  
  2957.     The elusive quality of "good style" involves much more than mere
  2958.     code layout details; don't spend time on formatting to the
  2959.     exclusion of more substantive code quality issues.
  2960.  
  2961.     References: K&R Sec. 1.2 p. 10.
  2962.  
  2963. 14.3:    Where can I get the "Indian Hill Style Guide" and other coding
  2964.     standards?
  2965.  
  2966. A:    Various documents are available for anonymous ftp from:
  2967.  
  2968.         Site:            File or directory:
  2969.  
  2970.         cs.washington.edu    ~ftp/pub/cstyle.tar.Z
  2971.         (128.95.1.4)        (the updated Indian Hill guide)
  2972.  
  2973.         cs.toronto.edu        doc/programming
  2974.  
  2975.         ftp.cs.umd.edu          pub/style-guide
  2976.  
  2977.  
  2978. Section 15. Floating Point
  2979.  
  2980. 15.1:    My floating-point calculations are acting strangely and giving
  2981.     me different answers on different machines.
  2982.  
  2983. A:    First, make sure that you have #included <math.h>, and correctly
  2984.     declared other functions returning double.
  2985.  
  2986.     If the problem isn't that simple, recall that most digital
  2987.     computers use floating-point formats which provide a close but
  2988.     by no means exact simulation of real number arithmetic.
  2989.     Underflow, cumulative precision loss, and other anomalies are
  2990.     often troublesome.
  2991.  
  2992.     Don't assume that floating-point results will be exact, and
  2993.     especially don't assume that floating-point values can be
  2994.     compared for equality.  (Don't throw haphazard "fuzz factors"
  2995.     in, either.)
  2996.  
  2997.     These problems are no worse for C than they are for any other
  2998.     computer language.  Floating-point semantics are usually defined
  2999.     as "however the processor does them;" otherwise a compiler for a
  3000.     machine without the "right" model would have to do prohibitively
  3001.     expensive emulations.
  3002.  
  3003.     This article cannot begin to list the pitfalls associated with,
  3004.     and workarounds appropriate for, floating-point work.  A good
  3005.     programming text should cover the basics.
  3006.  
  3007.     References: EoPS Sec. 6 pp. 115-8.
  3008.  
  3009. 15.2:    I'm trying to do some simple trig, and I am #including <math.h>,
  3010.     but I keep getting "undefined: _sin" compilation errors.
  3011.  
  3012. A:    Make sure you're linking with the correct math library.  For
  3013.     instance, under Unix, you usually need to use the -lm option,
  3014.     and at the _end_ of the command line, when compiling/linking.
  3015.     See also question 12.14.
  3016.  
  3017. 15.3:    Why doesn't C have an exponentiation operator?
  3018.  
  3019. A:    Because few processors have an exponentiation instruction.
  3020.     Instead, you can #include <math.h> and use the pow() function,
  3021.     although explicit multiplication is often better for small
  3022.     positive integral exponents.
  3023.  
  3024.     References: ANSI Sec. 4.5.5.1 .
  3025.  
  3026. 15.4:    How do I round numbers?
  3027.  
  3028. A:    The simplest and most straightforward way is with code like
  3029.  
  3030.         (int)(x + 0.5)
  3031.  
  3032.     This won't work properly for negative numbers, though.
  3033.  
  3034. 15.5:    How do I test for IEEE NaN and other special values?
  3035.  
  3036. A:    Many systems with high-quality IEEE floating-point
  3037.     implementations provide facilities (e.g. an isnan() macro) to
  3038.     deal with these values cleanly, and the Numerical C Extensions
  3039.     Group (NCEG) is working to formally standardize such facilities.
  3040.     A crude but usually effective test for NaN is exemplified by
  3041.  
  3042.         #define isnan(x) ((x) != (x))
  3043.  
  3044.     although non-IEEE-aware compilers may optimize the test away.
  3045.  
  3046. 15.6:    I'm having trouble with a Turbo C program which crashes and says
  3047.     something like "floating point formats not linked."
  3048.  
  3049. A:    Some compilers for small machines, including Turbo C (and
  3050.     Ritchie's original PDP-11 compiler), leave out floating point
  3051.     support if it looks like it will not be needed.  In particular,
  3052.     the non-floating-point versions of printf and scanf save space
  3053.     by not including code to handle %e, %f, and %g.  It happens that
  3054.     Turbo C's heuristics for determining whether the program uses
  3055.     floating point are insufficient, and the programmer must
  3056.     sometimes insert an extra, explicit call to a floating-point
  3057.     library routine to force loading of floating-point support.
  3058.  
  3059.  
  3060. Section 16. System Dependencies
  3061.  
  3062. 16.1:    How can I read a single character from the keyboard without
  3063.     waiting for a newline?
  3064.  
  3065. A:    Contrary to popular belief and many people's wishes, this is not
  3066.     a C-related question.  (Nor are closely-related questions
  3067.     concerning the echo of keyboard input.)  The delivery of
  3068.     characters from a "keyboard" to a C program is a function of the
  3069.     operating system in use, and has not been standardized by the C
  3070.     language.  Some versions of curses have a cbreak() function
  3071.     which does what you want.  If you're specifically trying to read
  3072.     a short password without echo, you might try getpass().  Under
  3073.     Unix, use ioctl to play with the terminal driver modes (CBREAK
  3074.     or RAW under "classic" versions; ICANON, c_cc[VMIN] and
  3075.     c_cc[VTIME] under System V or Posix systems).  Under MS-DOS, use
  3076.     getch().  Under VMS, try the Screen Management (SMG$) routines,
  3077.     or curses, or issue low-level $QIO's with the IO$_READVBLK (and
  3078.     perhaps IO$M_NOECHO) function codes to ask for one character at
  3079.     a time.  Under other operating systems, you're on your own.
  3080.     Beware that some operating systems make this sort of thing
  3081.     impossible, because character collection into input lines is
  3082.     done by peripheral processors not under direct control of the
  3083.     CPU running your program.
  3084.  
  3085.     Operating system specific questions are not appropriate for
  3086.     comp.lang.c .  Many common questions are answered in
  3087.     frequently-asked questions postings in such groups as
  3088.     comp.unix.questions and comp.os.msdos.programmer .  Note that
  3089.     the answers are often not unique even across different variants
  3090.     of a system; bear in mind when answering system-specific
  3091.     questions that the answer that applies to your system may not
  3092.     apply to everyone else's.
  3093.  
  3094.     References: PCS Sec. 10 pp. 128-9, Sec. 10.1 pp. 130-1.
  3095.  
  3096. 16.2:    How can I find out if there are characters available for reading
  3097.     (and if so, how many)?  Alternatively, how can I do a read that
  3098.     will not block if there are no characters available?
  3099.  
  3100. A:    These, too, are entirely operating-system-specific.  Some
  3101.     versions of curses have a nodelay() function.  Depending on your
  3102.     system, you may also be able to use "nonblocking I/O", or a
  3103.     system call named "select", or the FIONREAD ioctl, or kbhit(),
  3104.     or rdchk(), or the O_NDELAY option to open() or fcntl().
  3105.  
  3106. 16.3:    How can I clear the screen?  How can I print things in inverse
  3107.     video?
  3108.  
  3109. A:    Such things depend on the terminal type (or display) you're
  3110.     using.  You will have to use a library such as termcap or
  3111.     curses, or some system-specific routines, to perform these
  3112.     functions.
  3113.  
  3114. 16.4:    How do I read the mouse?
  3115.  
  3116. A:    Consult your system documentation, or ask on an appropriate
  3117.     system-specific newsgroup (but check its FAQ list first).  Mouse
  3118.     handling is completely different under the X window system, MS-
  3119.     DOS, Macintosh, and probably every other system.
  3120.  
  3121. 16.5:    How can my program discover the complete pathname to the
  3122.     executable file from which it was invoked?
  3123.  
  3124. A:    argv[0] may contain all or part of the pathname, or it may
  3125.     contain nothing.  You may be able to duplicate the command
  3126.     language interpreter's search path logic to locate the
  3127.     executable if the name in argv[0] is present but incomplete.
  3128.     However, there is no guaranteed or portable solution.
  3129.  
  3130. 16.6:    How can a process change an environment variable in its caller?
  3131.  
  3132. A:    In general, it cannot.  Different operating systems implement
  3133.     name/value functionality similar to the Unix environment in
  3134.     different ways.  Whether the "environment" can be usefully
  3135.     altered by a running program, and if so, how, is system-
  3136.     dependent.
  3137.  
  3138.     Under Unix, a process can modify its own environment (some
  3139.     systems provide setenv() and/or putenv() functions to do this),
  3140.     and the modified environment is usually passed on to any child
  3141.     processes, but it is _not_ propagated back to the parent
  3142.     process.
  3143.  
  3144. 16.7:    How can I check whether a file exists?  I want to query the user
  3145.     before overwriting existing files.
  3146.  
  3147. A:    On Unix-like systems, you can try the access() routine, although
  3148.     it's got a few problems.  (It isn't atomic with respect to the
  3149.     following action, and can have anomalies if used in setuid
  3150.     programs.)  Another option (perhaps preferable) is to call
  3151.     stat() on the file.  Otherwise, the only guaranteed and portable
  3152.     way to test for file existence is to try opening the file (which
  3153.     doesn't help if you're trying to avoid overwriting an existing
  3154.     file, unless you've got something like the BSD Unix O_EXCL open
  3155.     option available).
  3156.  
  3157. 16.8:    How can I find out the size of a file, prior to reading it in?
  3158.  
  3159. A:    If the "size of a file" is the number of characters you'll be
  3160.     able to read from it in C, it is in general impossible to
  3161.     determine this number in advance.  Under Unix, the stat call
  3162.     will give you an exact answer, and several other systems supply
  3163.     a Unix-like stat which will give an approximate answer.  You can
  3164.     fseek to the end and then use ftell, but this usage is
  3165.     nonportable (it gives you an accurate answer only under Unix,
  3166.     and otherwise a quasi-accurate answer only for ANSI C "binary"
  3167.     files).  Some systems provide routines called filesize or
  3168.     filelength.
  3169.  
  3170.     Are you sure you have to determine the file's size in advance?
  3171.     Since the most accurate way of determining the size of a file as
  3172.     a C program will see it is to open the file and read it, perhaps
  3173.     you can rearrange the code to learn the size as it reads.
  3174.  
  3175. 16.9:    How can a file be shortened in-place without completely clearing
  3176.     or rewriting it?
  3177.  
  3178. A:    BSD systems provide ftruncate(), several others supply chsize(),
  3179.     and a few may provide a (possibly undocumented) fcntl option
  3180.     F_FREESP.  Under MS-DOS, you can sometimes use write(fd, "", 0).
  3181.     However, there is no truly portable solution.
  3182.  
  3183. 16.10:    How can I implement a delay, or time a user's response, with
  3184.     sub-second resolution?
  3185.  
  3186. A:    Unfortunately, there is no portable way.  V7 Unix, and derived
  3187.     systems, provided a fairly useful ftime() routine with
  3188.     resolution up to a millisecond, but it has disappeared from
  3189.     System V and Posix.  Other routines you might look for on your
  3190.     system include nap(), setitimer(), msleep(), usleep(), clock(),
  3191.     and gettimeofday().  The select() and poll() calls (if
  3192.     available) can be pressed into service to implement simple
  3193.     delays.  On MS-DOS machines, it is possible to reprogram the
  3194.     system timer and timer interrupts.
  3195.  
  3196. 16.11:    How can I read in an object file and jump to routines in it?
  3197.  
  3198. A:    You want a dynamic linker and/or loader.  It is possible to
  3199.     malloc some space and read in object files, but you have to know
  3200.     an awful lot about object file formats, relocation, etc.  Under
  3201.     BSD Unix, you could use system() and ld -A to do the linking for
  3202.     you.  Many (most?) versions of SunOS and System V have the -ldl
  3203.     library which allows object files to be dynamically loaded.
  3204.     There is also a GNU package called "dld".  See also question
  3205.     7.6.
  3206.  
  3207. 16.12:    How can I invoke an operating system command from within a
  3208.     program?
  3209.  
  3210. A:    Use system().
  3211.  
  3212.     References: K&R II Sec. B6 p. 253; ANSI Sec. 4.10.4.5; H&S
  3213.     Sec. 21.2; PCS Sec. 11 p. 179;
  3214.  
  3215. 16.13:    How can I invoke an operating system command and trap its
  3216.     output?
  3217.  
  3218. A:    Unix and some other systems provide a popen() routine, which
  3219.     sets up a stdio stream on a pipe connected to the process
  3220.     running a command, so that the output can be read (or the input
  3221.     supplied).  Alternately, invoke the command simply (see question
  3222.     16.12) in such a way that it writes its output to a file, then
  3223.     open and read that file.
  3224.  
  3225.     References: PCS Sec. 11 p. 169 .
  3226.  
  3227. 16.14:    How can I read a directory in a C program?
  3228.  
  3229. A:    See if you can use the opendir() and readdir() routines, which
  3230.     are available on most Unix systems.  Implementations also exist
  3231.     for MS-DOS, VMS, and other systems.  (MS-DOS also has FINDFIRST
  3232.     and FINDNEXT routines which do essentially the same thing.)
  3233.  
  3234. 16.15:    How can I do serial ("comm") port I/O?
  3235.  
  3236. A:    It's system-dependent.  Under Unix, you typically open, read,
  3237.     and write a device in /dev, and use the facilities of the
  3238.     terminal driver to adjust its characteristics.  Under MS-DOS,
  3239.     you can either use some primitive BIOS interrupts, or (if you
  3240.     require decent performance) one of any number of interrupt-
  3241.     driven serial I/O packages.
  3242.  
  3243.  
  3244. Section 17. Miscellaneous
  3245.  
  3246. 17.1:    What can I safely assume about the initial values of variables
  3247.     which are not explicitly initialized?  If global variables start
  3248.     out as "zero," is that good enough for null pointers and
  3249.     floating-point zeroes?
  3250.  
  3251. A:    Variables with "static" duration (that is, those declared
  3252.     outside of functions, and those declared with the storage class
  3253.     static), are guaranteed initialized (just once, at program
  3254.     startup) to zero, as if the programmer had typed "= 0".
  3255.     Therefore, such variables are initialized to the null pointer
  3256.     (of the correct type; see also Section 1) if they are pointers,
  3257.     and to 0.0 if they are floating-point.
  3258.  
  3259.     Variables with "automatic" duration (i.e. local variables
  3260.     without the static storage class) start out containing garbage,
  3261.     unless they are explicitly initialized.  Nothing useful can be
  3262.     predicted about the garbage.
  3263.  
  3264.     Dynamically-allocated memory obtained with malloc and realloc is
  3265.     also likely to contain garbage, and must be initialized by the
  3266.     calling program, as appropriate.  Memory obtained with calloc
  3267.     contains all-bits-0, but this is not necessarily useful for
  3268.     pointer or floating-point values (see question 3.13, and section
  3269.     1).
  3270.  
  3271. 17.2:    This code, straight out of a book, isn't compiling:
  3272.  
  3273.         f()
  3274.         {
  3275.         char a[] = "Hello, world!";
  3276.         }
  3277.  
  3278. A:    Perhaps you have a pre-ANSI compiler, which doesn't allow
  3279.     initialization of "automatic aggregates" (i.e. non-static local
  3280.     arrays and structures).  As a workaround, you can make the array
  3281.     global or static, and initialize it with strcpy when f is
  3282.     called.  (You can always initialize local char * variables with
  3283.     string literals, but see question 17.20).  See also questions
  3284.     5.16 and 5.17.
  3285.  
  3286. 17.3:    How can I write data files which can be read on other machines
  3287.     with different word size, byte order, or floating point formats?
  3288.  
  3289. A:    The best solution is to use text files (usually ASCII), written
  3290.     with fprintf and read with fscanf or the like.  (Similar advice
  3291.     also applies to network protocols.)  Be skeptical of arguments
  3292.     which imply that text files are too big, or that reading and
  3293.     writing them is too slow.  Not only is their efficiency
  3294.     frequently acceptable in practice, but the advantages of being
  3295.     able to manipulate them with standard tools can be overwhelming.
  3296.  
  3297.     If you must use a binary format, you can improve portability,
  3298.     and perhaps take advantage of prewritten I/O libraries, by
  3299.     making use of standardized formats such as Sun's XDR (RFC 1014),
  3300.     OSI's ASN.1, CCITT's X.409, or ISO 8825 "Basic Encoding Rules."
  3301.     See also question 9.11.
  3302.  
  3303. 17.4:    How can I insert or delete a line (or record) in the middle of a
  3304.     file?
  3305.  
  3306. A:    Short of rewriting the file, you probably can't.  See also
  3307.     question 16.9.
  3308.  
  3309. 17.5:    How can I return several values from a function?
  3310.  
  3311. A:    Either pass pointers to locations which the function can fill
  3312.     in, or have the function return a structure containing the
  3313.     desired values, or (in a pinch) consider global variables.  See
  3314.     also questions 2.17, 3.4, and 9.2.
  3315.  
  3316. 17.6:    If I have a char * variable pointing to the name of a function
  3317.     as a string, how can I call that function?
  3318.  
  3319. A:    The most straightforward thing to do is maintain a
  3320.     correspondence table of names and function pointers:
  3321.  
  3322.         int function1(), function2();
  3323.  
  3324.         struct {char *name; int (*funcptr)(); } symtab[] =
  3325.             {
  3326.             "function1",    function1,
  3327.             "function2",    function2,
  3328.             };
  3329.  
  3330.     Then, just search the table for the name, and call through the
  3331.     associated function pointer.  See also questions 9.9 and 16.11.
  3332.  
  3333. 17.7:    I seem to be missing the system header file <sgtty.h>.  Can
  3334.     someone send me a copy?
  3335.  
  3336. A:    Standard headers exist in part so that definitions appropriate
  3337.     to your compiler, operating system, and processor can be
  3338.     supplied.  You cannot just pick up a copy of someone else's
  3339.     header file and expect it to work, unless that person is using
  3340.     exactly the same environment.  Ask your compiler vendor why the
  3341.     file was not provided (or to send a replacement copy).
  3342.  
  3343. 17.8:    How can I call FORTRAN (C++, BASIC, Pascal, Ada, LISP) functions
  3344.     from C?  (And vice versa?)
  3345.  
  3346. A:    The answer is entirely dependent on the machine and the specific
  3347.     calling sequences of the various compilers in use, and may not
  3348.     be possible at all.  Read your compiler documentation very
  3349.     carefully; sometimes there is a "mixed-language programming
  3350.     guide," although the techniques for passing arguments and
  3351.     ensuring correct run-time startup are often arcane.  More
  3352.     information may be found in FORT.gz by Glenn Geers, available
  3353.     via anonymous ftp from suphys.physics.su.oz.au in the src
  3354.     directory.
  3355.  
  3356.     cfortran.h, a C header file, simplifies C/FORTRAN interfacing on
  3357.     many popular machines.  It is available via anonymous ftp from
  3358.     zebra.desy.de (131.169.2.244).
  3359.  
  3360.     In C++, a "C" modifier in an external function declaration
  3361.     indicates that the function is to be called using C calling
  3362.     conventions.
  3363.  
  3364. 17.9:    Does anyone know of a program for converting Pascal or FORTRAN
  3365.     (or LISP, Ada, awk, "Old" C, ...) to C?
  3366.  
  3367. A:    Several public-domain programs are available:
  3368.  
  3369.     p2c    A Pascal to C converter written by Dave Gillespie,
  3370.         posted to comp.sources.unix in March, 1990 (Volume 21);
  3371.         also available by anonymous ftp from
  3372.         csvax.cs.caltech.edu, file pub/p2c-1.20.tar.Z .
  3373.  
  3374.     ptoc    Another Pascal to C converter, this one written in
  3375.         Pascal (comp.sources.unix, Volume 10, also patches in
  3376.         Volume 13?).
  3377.  
  3378.     f2c    A Fortran to C converter jointly developed by people
  3379.         from Bell Labs, Bellcore, and Carnegie Mellon.  To find
  3380.         out more about f2c, send the mail message "send index
  3381.         from f2c" to netlib@research.att.com or research!netlib.
  3382.         (It is also available via anonymous ftp on
  3383.         netlib.att.com, in directory netlib/f2c.)
  3384.  
  3385.     This FAQ list's maintainer also has available a list of other
  3386.     commercial translation products, and some for more obscure
  3387.     languages.
  3388.  
  3389.     See also question 5.3.
  3390.  
  3391. 17.10:    Is C++ a superset of C?  Can I use a C++ compiler to compile C
  3392.     code?
  3393.  
  3394. A:    C++ was derived from C, and is largely based on it, but there
  3395.     are some legal C constructs which are not legal C++.  (Many C
  3396.     programs will nevertheless compile correctly in a C++
  3397.     environment.)
  3398.  
  3399. 17.11:    I need:                A:  Look for programs (see also
  3400.                         question 17.12) named:
  3401.  
  3402.     a C cross-reference            cflow, calls, cscope
  3403.     generator
  3404.  
  3405.     a C beautifier/pretty-            cb, indent
  3406.     printer
  3407.  
  3408. 17.12:    Where can I get copies of all these public-domain programs?
  3409.  
  3410. A:    If you have access to Usenet, see the regular postings in the
  3411.     comp.sources.unix and comp.sources.misc newsgroups, which
  3412.     describe, in some detail, the archiving policies and how to
  3413.     retrieve copies.  The usual approach is to use anonymous ftp
  3414.     and/or uucp from a central, public-spirited site, such as uunet
  3415.     (ftp.uu.net, 192.48.96.9).  However, this article cannot track
  3416.     or list all of the available archive sites and how to access
  3417.     them.
  3418.  
  3419.     Ajay Shah maintains an index of free numerical software; it is
  3420.     posted periodically, and available where this FAQ list is
  3421.     archived (see question 17.33).  The comp.archives newsgroup
  3422.     contains numerous announcements of anonymous ftp availability of
  3423.     various items.  The "archie" mailserver can tell you which
  3424.     anonymous ftp sites have which packages; send the mail message
  3425.     "help" to archie@quiche.cs.mcgill.ca for information.  Finally,
  3426.     the newsgroup comp.sources.wanted is generally a more
  3427.     appropriate place to post queries for source availability, but
  3428.     check _its_ FAQ list, "How to find sources," before posting
  3429.     there.
  3430.  
  3431. 17.13:    When will the next International Obfuscated C Code Contest
  3432.     (IOCCC) be held?  How can I get a copy of the current and
  3433.     previous winning entries?
  3434.  
  3435. A:    The contest typically runs from early March through mid-May.  To
  3436.     obtain a current copy of the rules and guidelines, send e-mail
  3437.     with the Subject: line "send rules" to:
  3438.  
  3439.         {apple,pyramid,sun,uunet}!hoptoad!judges  or
  3440.         judges@toad.com
  3441.  
  3442.     (Note that these are _not_ the addresses for submitting
  3443.     entries.)
  3444.  
  3445.     Contest winners are first announced at the Summer Usenix
  3446.     Conference in mid-June, and posted to the net sometime in July-
  3447.     August.  Winning entries from previous years (to 1984) are
  3448.     archived at uunet (see question 17.12) under the directory
  3449.     ~/pub/ioccc.
  3450.  
  3451.     As a last resort, previous winners may be obtained by sending
  3452.     e-mail to the above address, using the Subject: "send YEAR
  3453.     winners", where YEAR is a single four-digit year, a year range,
  3454.     or "all".
  3455.  
  3456. 17.14:    Why don't C comments nest?  How am I supposed to comment out
  3457.     code containing comments?  Are comments legal inside quoted
  3458.     strings?
  3459.  
  3460. A:    Nested comments would cause more harm than good, mostly because
  3461.     of the possibility of accidentally leaving comments unclosed by
  3462.     including the characters "/*" within them.  For this reason, it
  3463.     is usually better to "comment out" large sections of code, which
  3464.     might contain comments, with #ifdef or #if 0 (but see question
  3465.     5.11).
  3466.  
  3467.     The character sequences /* and */ are not special within
  3468.     double-quoted strings, and do not therefore introduce comments,
  3469.     because a program (particularly one which is generating C code
  3470.     as output) might want to print them.
  3471.  
  3472.     References: ANSI Appendix E p. 198, Rationale Sec. 3.1.9 p. 33.
  3473.  
  3474. 17.15:    How can I get the ASCII value corresponding to a character, or
  3475.     vice versa?
  3476.  
  3477. A:    In C, characters are represented by small integers corresponding
  3478.     to their values (in the machine's character set) so you don't
  3479.     need a conversion routine: if you have the character, you have
  3480.     its value.
  3481.  
  3482. 17.16:    How can I implement sets and/or arrays of bits?
  3483.  
  3484. A:    Use arrays of char or int, with a few macros to access the right
  3485.     bit at the right index (try using 8 for CHAR_BIT if you don't
  3486.     have <limits.h>):
  3487.  
  3488.         #include <limits.h>        /* for CHAR_BIT */
  3489.  
  3490.         #define BITMASK(bit) (1 << ((bit) % CHAR_BIT))
  3491.         #define BITSLOT(bit) ((bit) / CHAR_BIT)
  3492.         #define BITSET(ary, bit) ((ary)[BITSLOT(bit)] |= BITMASK(bit))
  3493.         #define BITTEST(ary, bit) ((ary)[BITSLOT(bit)] & BITMASK(bit))
  3494.  
  3495. 17.17:    What is the most efficient way to count the number of bits which
  3496.     are set in a value?
  3497.  
  3498. A:    This and many other similar bit-twiddling problems can often be
  3499.     sped up and streamlined using lookup tables (but see the next
  3500.     question).
  3501.  
  3502. 17.18:    How can I make this code more efficient?
  3503.  
  3504. A:    Efficiency, though a favorite comp.lang.c topic, is not
  3505.     important nearly as often as people tend to think it is.  Most
  3506.     of the code in most programs is not time-critical.  When code is
  3507.     not time-critical, it is far more important that it be written
  3508.     clearly and portably than that it be written maximally
  3509.     efficiently.  (Remember that computers are very, very fast, and
  3510.     that even "inefficient" code can run without apparent delay.)
  3511.  
  3512.     It is notoriously difficult to predict what the "hot spots" in a
  3513.     program will be.  When efficiency is a concern, it is important
  3514.     to use profiling software to determine which parts of the
  3515.     program deserve attention.  Often, actual computation time is
  3516.     swamped by peripheral tasks such as I/O and memory allocation,
  3517.     which can be sped up by using buffering and caching techniques.
  3518.  
  3519.     For the small fraction of code that is time-critical, it is
  3520.     vital to pick a good algorithm; it is less important to
  3521.     "microoptimize" the coding details.  Many of the "efficient
  3522.     coding tricks" which are frequently suggested (e.g. substituting
  3523.     shift operators for multiplication by powers of two) are
  3524.     performed automatically by even simpleminded compilers.
  3525.     Heavyhanded "optimization" attempts can make code so bulky that
  3526.     performance is degraded.
  3527.  
  3528.     For more discussion of efficiency tradeoffs, as well as good
  3529.     advice on how to increase efficiency when it is important, see
  3530.     chapter 7 of Kernighan and Plauger's The Elements of Programming
  3531.     Style, and Jon Bentley's Writing Efficient Programs.
  3532.  
  3533. 17.19:    Are pointers really faster than arrays?  How much do function
  3534.     calls slow things down?  Is ++i faster than i = i + 1?
  3535.  
  3536. A:    Precise answers to these and many similar questions depend of
  3537.     course on the processor and compiler in use.  If you simply must
  3538.     know, you'll have to time test programs carefully.  (Often the
  3539.     differences are so slight that hundreds of thousands of
  3540.     iterations are required even to see them.  Check the compiler's
  3541.     assembly language output, if available, to see if two purported
  3542.     alternatives aren't compiled identically.)
  3543.  
  3544.     It is "usually" faster to march through large arrays with
  3545.     pointers rather than array subscripts, but for some processors
  3546.     the reverse is true.
  3547.  
  3548.     Function calls, though obviously incrementally slower than in-
  3549.     line code, contribute so much to modularity and code clarity
  3550.     that there is rarely good reason to avoid them.
  3551.  
  3552.     Before rearranging expressions such as i = i + 1, remember that
  3553.     you are dealing with a C compiler, not a keystroke-programmable
  3554.     calculator.  Any decent compiler will generate identical code
  3555.     for ++i, i += 1, and i = i + 1.  The reasons for using ++i or
  3556.     i += 1 over i = i + 1 have to do with style, not efficiency.
  3557.     (See also question 4.7.)
  3558.  
  3559. 17.20:    Why does this code:
  3560.  
  3561.         char *p = "Hello, world!";
  3562.         p[0] = tolower(p[0]);
  3563.  
  3564.     crash?
  3565.  
  3566. A:    String literals are not necessarily modifiable, except (in
  3567.     effect) when they are used as array initializers.  Try
  3568.  
  3569.         char a[] = "Hello, world!";
  3570.  
  3571.     (For compiling old code, some compilers have a switch
  3572.     controlling whether strings are writable or not.)  See also
  3573.     questions 2.1, 2.2, 2.8, and 17.2.
  3574.  
  3575.     References: ANSI Sec. 3.1.4 .
  3576.  
  3577. 17.21:    This program crashes before it even runs!  (When single-stepping
  3578.     with a debugger, it dies before the first statement in main.)
  3579.  
  3580. A:    You probably have one or more very large (kilobyte or more)
  3581.     local arrays.  Many systems have fixed-size stacks, and those
  3582.     which perform dynamic stack allocation automatically (e.g. Unix)
  3583.     can be confused when the stack tries to grow by a huge chunk all
  3584.     at once.
  3585.  
  3586.     It is often better to declare large arrays with static duration
  3587.     (unless of course you need a fresh set with each recursive
  3588.     call).
  3589.  
  3590.     (See also question 9.4.)
  3591.  
  3592. 17.22:    What do "Segmentation violation" and "Bus error" mean?
  3593.  
  3594. A:    These generally mean that your program tried to access memory it
  3595.     shouldn't have, invariably as a result of improper pointer use,
  3596.     often involving uninitialized or improperly allocated pointers
  3597.     (see questions 3.1 and 3.2), or malloc (see question 17.23), or
  3598.     perhaps scanf (see question 11.3).
  3599.  
  3600. 17.23:    My program is crashing, apparently somewhere down inside malloc,
  3601.     but I can't see anything wrong with it.
  3602.  
  3603. A:    It is unfortunately very easy to corrupt malloc's internal data
  3604.     structures, and the resulting problems can be hard to track
  3605.     down.  The most common source of problems is writing more to a
  3606.     malloc'ed region than it was allocated to hold; a particularly
  3607.     common bug is to malloc(strlen(s)) instead of strlen(s) + 1.
  3608.     Other problems involve freeing pointers not obtained from
  3609.     malloc, or trying to realloc a null pointer (see question 3.12).
  3610.  
  3611.     A number of debugging packages exist to help track down malloc
  3612.     problems; one popular one is Conor P. Cahill's "dbmalloc,"
  3613.     posted to comp.sources.misc in September of 1992.  Others are
  3614.     "leak," available in volume 27 of the comp.sources.unix
  3615.     archives; JMalloc.c and JMalloc.h in Fidonet's C_ECHO Snippets
  3616.     (or ask archie; see question 17.12); and MEMDEBUG from
  3617.     ftp.crpht.lu in pub/sources/memdebug .  See also question 17.12.
  3618.  
  3619. 17.24:    Does anyone have a C compiler test suite I can use?
  3620.  
  3621. A:    Plum Hall (formerly in Cardiff, NJ; now in Hawaii) sells one.
  3622.     The FSF's GNU C (gcc) distribution includes a c-torture-
  3623.     test.tar.Z which checks a number of common problems with
  3624.     compilers.  Kahan's paranoia test, found in netlib/paranoia on
  3625.     netlib.att.com, strenuously tests a C implementation's floating
  3626.     point capabilities.
  3627.  
  3628. 17.25:    Where can I get a YACC grammar for C?
  3629.  
  3630. A:    The definitive grammar is of course the one in the ANSI
  3631.     standard.  Another grammar, by Jim Roskind, is in pub/*grammar*
  3632.     at ics.uci.edu .  A fleshed-out, working instance of the ANSI
  3633.     grammar (due to Jeff Lee) is on uunet (see question 17.12) in
  3634.     usenet/net.sources/ansi.c.grammar.Z (including a companion
  3635.     lexer).  The FSF's GNU C compiler contains a grammar, as does
  3636.     the appendix to K&R II.
  3637.  
  3638.     References: ANSI Sec. A.2 .
  3639.  
  3640. 17.26:    I need code to parse and evaluate expressions.
  3641.  
  3642. A:    Two available packages are "defunc," posted to comp.source.misc
  3643.     in December, 1993 (V41 i32,33), to alt.sources in January, 1994,
  3644.     and available from sunsite.unc.edu in
  3645.     pub/packages/development/libraries/defunc-1.3.tar.Z; and
  3646.     "parse," at lamont.ldgo.columbia.edu.
  3647.  
  3648. 17.27:    I need a sort of an "approximate" strcmp routine, for comparing
  3649.     two strings for close, but not necessarily exact, equality.
  3650.  
  3651. A:    The traditional routine for doing this sort of thing involves
  3652.     the "soundex" algorithm, which maps similar-sounding words to
  3653.     the same numeric codes.  Soundex is described in the Searching
  3654.     and Sorting volume of Donald Knuth's classic _The Art of
  3655.     Computer Programming_.
  3656.  
  3657. 17.28:    How can I find the day of the week given the date?
  3658.  
  3659. A:    Use mktime (see questions 12.6 and 12.7), or Zeller's
  3660.     congruence, or see the sci.math FAQ list, or try this code
  3661.     posted by Tomohiko Sakamoto:
  3662.  
  3663.         dayofweek(y, m, d)    /* 0 = Sunday */
  3664.         int y, m, d;        /* 1 <= m <= 12,  y > 1752 or so */
  3665.         {
  3666.             static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
  3667.             y -= m < 3;
  3668.             return (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
  3669.         }
  3670.  
  3671. 17.29:    Will 2000 be a leap year?  Is (year % 4 == 0) an accurate test
  3672.     for leap years?
  3673.  
  3674. A:    Yes and no, respectively.  The full expression for the Gregorian
  3675.     calendar is
  3676.  
  3677.         year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
  3678.  
  3679.     See a good astronomical almanac or other reference for details.
  3680.  
  3681. 17.30:    How do you pronounce "char"?
  3682.  
  3683. A:    You can pronounce the C keyword "char" in at least three ways:
  3684.     like the English words "char," "care," or "car;" the choice is
  3685.     arbitrary.
  3686.  
  3687. 17.31:    What's a good book for learning C?
  3688.  
  3689. A:    Mitch Wright maintains an annotated bibliography of C and Unix
  3690.     books; it is available for anonymous ftp from ftp.rahul.net in
  3691.     directory pub/mitch/YABL.
  3692.  
  3693.     This FAQ list's editor maintains a collection of previous
  3694.     answers to this question, which is available upon request.
  3695.  
  3696. 17.32:    Are there any C tutorials on the net?
  3697.  
  3698. A:    There are at least two of them:
  3699.  
  3700.     "Notes for C programmers," by Christopher Sawtell,
  3701.     available from:
  3702.     svr-ftp.eng.cam.ac.uk:misc/sawtell_C.shar
  3703.     garbo.uwasa.fi:/pc/c-lang/c-lesson.zip
  3704.     paris7.jussieu.fr:/contributions/docs
  3705.  
  3706.     Tim Love's "C for Programmers,"
  3707.     available from svr-ftp.eng.cam.ac.uk in the misc directory.
  3708.  
  3709. 17.33:    Where can I get extra copies of this list?  What about back
  3710.     issues?
  3711.  
  3712. A:    For now, just pull it off the net; it is normally posted to
  3713.     comp.lang.c on the first of each month, with an Expires: line
  3714.     which should keep it around all month.  An abridged version is
  3715.     also available (and posted), as is a list of changes
  3716.     accompanying each significantly updated version.  These lists
  3717.     can also be found in the newsgroups comp.answers and
  3718.     news.answers .  Several sites archive news.answers postings and
  3719.     other FAQ lists, including this one; two sites are rtfm.mit.edu
  3720.     (directories pub/usenet/news.answers/C-faq/ and
  3721.     pub/usenet/comp.lang.c/ ) and ftp.uu.net (directory
  3722.     usenet/news.answers/C-faq/ ).  The archie server should help you
  3723.     find others; query it for "prog C-faq".  See the meta-FAQ list
  3724.     in news.answers for more information; see also question 17.12.
  3725.  
  3726.     This list is an evolving document of questions which have been
  3727.     Frequent since before the Great Renaming, not just a collection
  3728.     of this month's interesting questions.  Older copies are
  3729.     obsolete and don't contain much, except the occasional typo,
  3730.     that the current list doesn't.
  3731.  
  3732.  
  3733. Bibliography
  3734.  
  3735. ANSI    American National Standard for Information Systems --
  3736.     Programming Language -- C, ANSI X3.159-1989 (see question 5.2).
  3737.  
  3738. JLB    Jon Louis Bentley, Writing Efficient Programs, Prentice-Hall,
  3739.     1982, ISBN 0-13-970244-X.
  3740.  
  3741. H&S    Samuel P. Harbison and Guy L. Steele, C: A Reference Manual,
  3742.     Second Edition, Prentice-Hall, 1987, ISBN 0-13-109802-0.  (A
  3743.     third edition has recently been released.)
  3744.  
  3745. PCS    Mark R. Horton, Portable C Software, Prentice Hall, 1990,
  3746.     ISBN 0-13-868050-7.
  3747.  
  3748. EoPS    Brian W. Kernighan and P.J. Plauger, The Elements of Programming
  3749.     Style, Second Edition, McGraw-Hill, 1978, ISBN 0-07-034207-5.
  3750.  
  3751. K&R I    Brian W. Kernighan and Dennis M. Ritchie, The C Programming
  3752.     Language, Prentice-Hall, 1978, ISBN 0-13-110163-3.
  3753.  
  3754. K&R II    Brian W. Kernighan and Dennis M. Ritchie, The C Programming
  3755.     Language, Second Edition, Prentice Hall, 1988, ISBN 0-13-
  3756.     110362-8, 0-13-110370-9.
  3757.  
  3758. Knuth    Donald E. Knuth, The Art of Computer Programming, (3 vols.),
  3759.     Addison-Wesley, 1981.
  3760.  
  3761. CT&P    Andrew Koenig, C Traps and Pitfalls, Addison-Wesley, 1989,
  3762.     ISBN 0-201-17928-8.
  3763.  
  3764.     P.J. Plauger, The Standard C Library, Prentice Hall, 1992,
  3765.     ISBN 0-13-131509-9.
  3766.  
  3767.     Harry Rabinowitz and Chaim Schaap, Portable C, Prentice-Hall,
  3768.     1990, ISBN 0-13-685967-4.
  3769.  
  3770. There is a more extensive bibliography in the revised Indian Hill style
  3771. guide (see question 14.3).  See also question 17.31.
  3772.  
  3773.  
  3774. Acknowledgements
  3775.  
  3776. Thanks to Jamshid Afshar, Sudheer Apte, Randall Atkinson, Dan Bernstein,
  3777. Vincent Broman, Stan Brown, Joe Buehler, Gordon Burditt, Burkhard Burow,
  3778. Conor P. Cahill, D'Arcy J.M. Cain, Christopher Calabrese, Ian Cargill,
  3779. Paul Carter, Billy Chambless, Raymond Chen, Jonathan Coxhead, Lee
  3780. Crawford, Steve Dahmer, Andrew Daviel, James Davies, Jutta Degener, Norm
  3781. Diamond, Jeff Dunlop, Ray Dunn, Stephen M. Dunn, Michael J. Eager, Dave
  3782. Eisen, Bjorn Engsig, Chris Flatters, Rod Flores, Alexander Forst, Jeff
  3783. Francis, Dave Gillespie, Samuel Goldstein, Alasdair Grant, Ron
  3784. Guilmette, Doug Gwyn, Tony Hansen, Joe Harrington, Guy Harris, Elliotte
  3785. Rusty Harold, Jos Horsmeier, Blair Houghton, Ke Jin, Kirk Johnson, Larry
  3786. Jones, Kin-ichi Kitano, Peter Klausler, Andrew Koenig, Tom Koenig, Ajoy
  3787. Krishnan T, Markus Kuhn, John Lauro, Felix Lee, Mike Lee, Timothy J.
  3788. Lee, Tony Lee, Don Libes, Christopher Lott, Tim Love, Tim McDaniel,
  3789. Stuart MacMartin, John R. MacMillan, Bob Makowski, Evan Manning, Barry
  3790. Margolin, George Matas, Brad Mears, Bill Mitchell, Mark Moraes, Darren
  3791. Morby, Ken Nakata, Landon Curt Noll, David O'Brien, Richard A. O'Keefe,
  3792. Hans Olsson, Philip (lijnzaad@embl-heidelberg.de), Andrew Phillips,
  3793. Christopher Phillips, Francois Pinard, Dan Pop, Kevin D. Quitt, Pat
  3794. Rankin, J. M. Rosenstock, Erkki Ruohtula, Tomohiko Sakamoto, Rich Salz,
  3795. Chip Salzenberg, Paul Sand, DaviD W. Sanderson, Christopher Sawtell,
  3796. Paul Schlyter, Doug Schmidt, Rene Schmit, Russell Schulz, Patricia
  3797. Shanahan, Peter da Silva, Joshua Simons, Henry Spencer, David Spuler,
  3798. Melanie Summit, Erik Talvola, Clarke Thatcher, Wayne Throop, Chris
  3799. Torek, Andrew Tucker, Goran Uddeborg, Rodrigo Vanegas, Jim Van Zandt,
  3800. Wietse Venema, Ed Vielmetti, Larry Virden, Chris Volpe, Mark Warren,
  3801. Larry Weiss, Freek Wiedijk, Lars Wirzenius, Dave Wolverton, Mitch
  3802. Wright, Conway Yee, and Zhuo Zang, who have contributed, directly or
  3803. indirectly, to this article.  Special thanks to Karl Heuer, and
  3804. particularly to Mark Brader, who (to borrow a line from Steve Johnson)
  3805. have goaded me beyond my inclination, and occasionally beyond my
  3806. endurance, in relentless pursuit of a better FAQ list.
  3807.  
  3808.                     Steve Summit
  3809.                     scs@eskimo.com
  3810.  
  3811. This article is Copyright 1988, 1990-1994 by Steve Summit.
  3812. It may be freely redistributed so long as the author's name, and this
  3813. notice, are retained.
  3814. The C code in this article (vstrcat(), error(), etc.) is public domain
  3815. and may be used without restriction.
  3816.  
  3817.